I wrote code that can write and read data from physical disk. I open the physical disk using pInvoke CreateFile and use FileStream to perform read and write data.
When physical disk is online, every thing works great.
In case the physical disk is offline and I try to write to disk, I get an error System.IO.IOException: 'The media is write protected.'
How can I detect if disk is offline without trying to write to disk.
Here is the code that create the FileStream and perform writes to disk
private const uint GENERIC_READ = 0x80000000;
private const uint GENERIC_WRITE = 0x40000000;
private const uint OPEN_EXISTING = 3;
private const uint FILE_FLAG_NO_BUFFERING = 0x20000000;
private const uint FILE_FLAG_WRITE_THROUGH = 0x80000000;
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string lpFileName, uint dwDesiredAccess,
uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,
uint dwFlagsAndAttributes, IntPtr hTemplateFile);
public void OpenFile()
{
m_handleValue = CreateFile(DevicePath, GENERIC_WRITE | GENERIC_READ,
0x3, IntPtr.Zero, OPEN_EXISTING,
FILE_FLAG_NO_BUFFERING | FILE_FLAG_WRITE_THROUGH
, IntPtr.Zero);
m_fileStream = new FileStream(m_handleValue, FileAccess.ReadWrite, 512);
}
public void WriteData(int offset, byte[] data)
{
m_fileStream.Seek(offset, SeekOrigin.Begin);
m_fileStream.Write(data, 0, data.Length);
}