Skip to content

Instantly share code, notes, and snippets.

@thomaslevesque
Created August 12, 2013 13:00
Show Gist options
  • Save thomaslevesque/6210607 to your computer and use it in GitHub Desktop.
Save thomaslevesque/6210607 to your computer and use it in GitHub Desktop.
Class that gives access to NTFS Alternate Data Streams
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace ADS
{
public static class AlternateDataStream
{
public static FileStream Open(string path, string streamName, FileMode mode)
{
return Open(path, streamName, mode, (mode == FileMode.Append) ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None);
}
public static FileStream Open(string path, string streamName, FileMode mode, FileAccess access)
{
return Open(path, streamName, mode, access, FileShare.None);
}
public static FileStream Open(string path, string streamName, FileMode mode, FileAccess access, FileShare share)
{
string fullPath = AppendStreamName(path, streamName);
var handle = NativeMethods.CreateFile(fullPath, (uint) access, (uint) share, IntPtr.Zero, (uint) mode, 0, IntPtr.Zero);
if (handle.IsInvalid)
{
var hr = Marshal.GetHRForLastWin32Error();
Marshal.ThrowExceptionForHR(hr);
}
return new FileStream(handle, access);
}
public static FileStream OpenRead(string path, string streamName)
{
return Open(path, streamName, FileMode.Open, FileAccess.Read, FileShare.Read);
}
public static FileStream OpenWrite(string path, string streamName)
{
return Open(path, streamName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
}
public static void Delete(string path, string streamName)
{
string fullPath = AppendStreamName(path, streamName);
NativeMethods.DeleteFile(fullPath);
}
private static string AppendStreamName(string fileName, string streamName)
{
return fileName + ":" + streamName;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment