I'm successfully past problem of getting the device to enumarate and getting the file handle
However the fileStream Read/Write doesn't work
I used the managed file stream method i.e first create a handle via native call in overlapped mode. Then use the handle to get a FileStream object and perform read/write using it. On XP 32 bit it works great but on Windows 7 the FileStream.Write throws a null reference exception.
Then on Windows 7 the approach I took was read/write using native calls (I abandoned the managed FileStream class approach). For this I used WriteFile, ReadFile, GetOverlappedResult APIs with OVERLAPPED structure etc. I have also pinned the data buffers. But ReadFile (or WriteFile) returns 997 i.e ERROR_IO_PENDING and subsequent call to GetOverlappedResult returns 1 ie. ERROR_INVALID_FUNCTION. Then NumberOfBytesRead is always 0.
Im not sure what am I doing wrong!!!.
Following is a code snippet containing the read API.
Thanks In advance for all the help.
Expand|Select|Wrap|Line Numbers
- public byte[] Read()
- {
- OVERLAPPED ovlpd = new OVERLAPPED();
- byte [] buffer = new byte[512];
- int ErrorCode = 0;
- uint NumberOfBytesRead = 0;
- const uint ERROR_IO_PENDING = 997;
- GCHandle PinnedBuffer = GCHandle.Alloc(buffer, GCHandleType.Pinned);
- ovlpd.Offset = 0;
- ovlpd.OffsetHigh = 0;
- ovlpd.EventHandle = ewhRead.SafeWaitHandle.DangerousGetHandle();
- ovlpd.Internal = UIntPtr.Zero;
- ovlpd.InternalHigh = UIntPtr.Zero;
- GCHandle PinnedOvlpd = GCHandle.Alloc(ovlpd, GCHandleType.Pinned);
- // ewhRead is declared and instantiate outside
- // EventWaitHandle ewhRead = new EventWaitHandle(false, EventResetMode.ManualReset);
- ewhRead.Reset();
- if(ReadFile(m_hDevFsHandle,
- PinnedBuffer.AddrOfPinnedObject(),
- (uint) 512,
- out NumberOfBytesRead,
- PinnedOvlpd.AddrOfPinnedObject()))
- {
- ErrorCode = Marshal.GetLastWin32Error();
- Dbg.WriteLine("Read Success: {0}", ErrorCode);
- }
- else
- {
- ErrorCode = Marshal.GetLastWin32Error();
- Dbg.WriteLine("Read Error: {0}", ErrorCode);
- if (ErrorCode == ERROR_IO_PENDING)
- {
- if (!ewhRead.WaitOne(5000))
- {
- Dbg.WriteLine("Wait Timed out");
- }
- if (0 != GetOverlappedResult(m_hDevFsHandle,
- PinnedOvlpd.AddrOfPinnedObject(),
- out NumberOfBytesRead,
- 1))
- {
- ErrorCode = Marshal.GetLastWin32Error();
- Dbg.WriteLine("GetOverlappedResult Success: {0}", ErrorCode);
- }
- else
- {
- ErrorCode = Marshal.GetLastWin32Error();
- Dbg.WriteLine("GetOverlappedResult Error: {0}", ErrorCode);
- }
- }
- else
- {
- CancelIo(m_hDevFsHandle);
- }
- Dbg.WriteLine("Read {0}", NumberOfBytesRead);
- }
- PinnedBuffer.Free();
- PinnedOvlpd.Free();
- return buffer;
- }