If you try to open a drive directly with C# classes (like FileStream) you will encounter a runtime error. Basically what you want to do is open the file „\\.\X:“ for a single partition, or if you want to gain access to the physical drive with the partition table and everything „\\.\PhysicalDrive0“. This will result in:
“FileStream will not open Win32 devices such as disk partitions and tape drives. Avoid use of „\\.\“ in the path.”
Some confusion might occur when you try to open a „normal“ path and still receive some error messages, there are still some reserved keywords which cannot be used (like PRN or CON).
To get around this problem, what you have to do is take a P/Invoke to call the Win32-API function CreateFile() from kernel32.dll.
To reach this goal you need some using statements, and then the CreateFile() signature in your class. Following code snippet should give you an idea on how to implement this:
// Import possibility to gather raw access to devices
// with global \\.\ paths which is prohibited by normal
// .NET <cref>FileStream</cref> class.
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern SafeFileHandle CreateFile(
[MarshalAs(UnmanagedType.U4)] FileAccess fileAccess,
[MarshalAs(UnmanagedType.U4)] FileShare fileShare,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] FileAttributes fileAttributes,
SafeFileHandle driveHandle = CreateFile(@"\\.\X:",
FileShare.ReadWrite, // drives must be opened with read and write share access
throw new Win32Exception(Marshal.GetLastWin32Error());
// using will prevent the handle to be closed automatically
using (FileStream InStream = new FileStream(driveHandle, FileAccess.Read))
// do some stuff on the stream
In this example I open the partition X: for read access. You should know very exactly what you do if you open it for write access. Of course this code will no longer be portable to other platforms as kernel32.dll is Windows specific. Also note, that your program may need Administrator privileges to open Win32-Devices as noted in the MSDN (please read that small article carefully).
Information on how to implement this were taken from pinvoke.net which gives generally a good overview on how to get access to Win32-API functions.
Also note that I’m not a professional Windows-Programmer and the code provided may be erroneous, unsafe and cause damage to a system, you use this at your own risk. This is only intended to give you a starting point on how to approach this problem.