Gaining access to the File Allocation Table in C# or any other direct drive access

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
...
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.IO;
using System.ComponentModel;
...
class XYZ
{
    // 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(
        string fileName,
        [MarshalAs(UnmanagedType.U4)] FileAccess fileAccess,
        [MarshalAs(UnmanagedType.U4)] FileShare fileShare,
        int securityAttributes,
        [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
        [MarshalAs(UnmanagedType.U4)] FileAttributes fileAttributes,
        IntPtr template);
    ...
    void MyUseFunction()
    {
        SafeFileHandle driveHandle = CreateFile(@"\\.\X:",
            FileAccess.Read,
            FileShare.ReadWrite, // drives must be opened with read and write share access
            0,
            FileMode.Open,
            FileAttributes.Normal,
            IntPtr.Zero);

        if (driveHandle.IsInvalid)
        {
            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.

1 Stern2 Sterne3 Sterne4 Sterne5 Sterne (keine Bewertung bisher)
Loading...

Tags: , ,

Sonntag, 27. Februar 2011 Computer, Software

3 Comments zu Gaining access to the File Allocation Table in C# or any other direct drive access

  • Ark-kun sagt:

    >//using will prevent the handle to be closed automatically
    This comment is WRONG. Using just calls the Dispose method after you’re finished with the object. http://msdn.microsoft.com/en-us/library/yh598w02.aspx

    • Arsenal sagt:

      It’s been quite a while, since I coded that. But if I remember correctly I had troubles with the handle being closed automatically before I was done using it, and the using statement prevented that nicely, as a side effect of what is described in the link you posted. But probably I am doing something wrong with the handle in the first place. I’m not that good with C#.

  • Lorax sagt:

    Thanks so much, i realy need this.

  • Kommentar abgeben

     
    profile for Arsenal on Stack Exchange, a network of free, community-driven Q&A sites

    PayPal-Spende



    • Hosted by netcup.de

    Durch die weitere Nutzung der Seite stimmst du der Verwendung von Cookies zu. Weitere Informationen

    Die Cookie-Einstellungen auf dieser Website sind auf "Cookies zulassen" eingestellt, um das beste Surferlebnis zu ermöglichen. Wenn du diese Website ohne Änderung der Cookie-Einstellungen verwendest oder auf "Akzeptieren" klickst, erklärst du sich damit einverstanden.

    Schließen