I need to open read disk in raw mode, so I'm using CreateFile API function for that purposes.
private static FileStream OpenDisk(string drive)
{
// Try to open hard disk drive in raw mode for reading
SafeFileHandle safeHandle = Native.CreateFile(
string.Format(@"\\.\{0}", drive),
FileAccess.Read,
FileShare.Read,
IntPtr.Zero,
FileMode.Open,
FileAttributes.ReadOnly | FileAttributes.Device,
IntPtr.Zero);
// Check if the drive was successfully opened
if (safeHandle.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
// Create file stream on the file for reading
return new FileStream(safeHandle, FileAccess.Read);
}
But when I try to read from the stream I get the following error
Handle does not support synchronous operations. The parameters to the FileStream constructor may need to be changed to indicate that the handle was opened asynchronously (that is, it was opened explicitly for overlapped I/O).
Here is the sample code that reproduces this issue
using (FileStream stream = OpenDisk("X:"))
{
byte[] buffer = new byte[1000];
while (stream.Read(buffer, 0, 1000) > 0) { }
}
I don't really get what does it want from me? It works when I use larger buffer (for example 4096). When I say it works I mean it really works (always), it was working for a while, until I changed buffer size. I guess it does some kind of asynchronous buffering inside and when I specify larger buffer then default buffering size it's just not used, but how to get rid of this?
Thanks
update
When I try to read it using BufferedStream I get the same issue
using (BufferedStream stream = new BufferedStream(OpenDisk("X:"), 4096))
{
byte[] buffer = new byte[1000];
while (stream.Read(buffer, 0, 1000) > 0) { }
}
Do I understand wrong purpose of BufferedStream? Shouldn't it read and cache chunks of specified size?