CreateFile Sector/Block level equivalent

  • Thread starter Thread starter Scott Bell
  • Start date Start date
S

Scott Bell

Hello all,

What is the equivalent in the .NET Framework for accessing
a device at the block/sector level such as one would when
using CreateFile on a device like "\\.\D:"? Attempting to create
a BinaryReader on a FileStream opened (read-only) on "D:"
yields an Access Denied exception.

Thanks,

- Scott
 
Scott said:
Hello all,

What is the equivalent in the .NET Framework for accessing
a device at the block/sector level such as one would when
using CreateFile on a device like "\\.\D:"? Attempting to create
a BinaryReader on a FileStream opened (read-only) on "D:"
yields an Access Denied exception.

Use P/Invoke to call CreateFile and ReadFile directly passing in the
appropriate options to open a device.

http://www.pinvoke.net/default.aspx/kernel32/CreateFile.html
http://www.pinvoke.net/default.aspx/kernel32/ReadFile.html

-cd
 
"Carl Daniel [VC++ MVP]" <[email protected]>
wrote in message | Scott Bell wrote:
| > Hello all,
| >
| > What is the equivalent in the .NET Framework for accessing
| > a device at the block/sector level such as one would when
| > using CreateFile on a device like "\\.\D:"? Attempting to create
| > a BinaryReader on a FileStream opened (read-only) on "D:"
| > yields an Access Denied exception.
|
| Use P/Invoke to call CreateFile and ReadFile directly passing in the
| appropriate options to open a device.
|
| http://www.pinvoke.net/default.aspx/kernel32/CreateFile.html
| http://www.pinvoke.net/default.aspx/kernel32/ReadFile.html
|
| -cd
|
|

Note that there is no need to Pinvoke Win32's ReadFile, the handle (use a
SafeHandle in V2) returned by CreateFile can be used to create a FileStream,
this class has a number of contructor overloads that take an IntPtr
(representing the handle) or a SafeHandle.

Willy.
 
Willy,

Thanks, the following worked out to be the most ideal:

[DllImport("Kernel32.dll", SetLastError = true, CharSet =
CharSet.Auto)]
static extern SafeFileHandle CreateFile(
string fileName,
[MarshalAs(UnmanagedType.U4)] FileAccess fileAccess,
[MarshalAs(UnmanagedType.U4)] FileShare fileShare,
int securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
int flags,
IntPtr template);

- Scott
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top