<p>Is it possible to read a disk directly with .NET?  By directly, I mean via the device bypassing the file system.  I think I would go about this by opening the device some way &quot;\Device\Ide\IdeDeviceP2T0L0-1&quot; for example.</p>
<p>If I can't open the device with a .NET API, knowing which Win32 API to use would be helpful.</p>

[{'answer_id': 38213, 'author': 'Mark Brackett', 'author_id': 2199, 'author_profile': 'https://Stackoverflow.com/users/2199', 'pm_score': 4, 'selected': True, 'text': '<p><a href="http://msdn.microsoft.com/en-us/library/aa363858.aspx" rel="noreferrer">CreateFile</a> has support for direct disk access. Read the notes under "Physical Disks and Volumes". You should be able to P/Invoke the call.</p>\n\n<p>Note that Vista and Server 2008 have <a href="http://support.microsoft.com/kb/942448" rel="noreferrer">severely restricted</a> this.</p>\n'}, {'answer_id': 38275, 'author': 'Darryl Braaten', 'author_id': 1834, 'author_profile': 'https://Stackoverflow.com/users/1834', 'pm_score': 4, 'selected': False, 'text': '<p>Cool, thank you Mark, I had forgotten that CreateFile opens things too.  I was looking at the volume management API and not seeing how to open things.  </p>\n\n<p>Here is a little class that wraps things up.  It might also be possible/correct to just pass the SafeFileHandle into a FileStream.</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\nusing System.IO;\nusing Microsoft.Win32.SafeHandles;\n\nnamespace ReadFromDevice\n{\n    public class DeviceStream : Stream, IDisposable\n    {\n        public const short FILE_ATTRIBUTE_NORMAL = 0x80;\n        public const short INVALID_HANDLE_VALUE = -1;\n        public const uint GENERIC_READ = 0x80000000;\n        public const uint GENERIC_WRITE = 0x40000000;\n        public const uint CREATE_NEW = 1;\n        public const uint CREATE_ALWAYS = 2;\n        public const uint OPEN_EXISTING = 3;\n\n        // Use interop to call the CreateFile function.\n        // For more information about CreateFile,\n        // see the unmanaged MSDN reference library.\n        [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]\n        private static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess,\n          uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition,\n          uint dwFlagsAndAttributes, IntPtr hTemplateFile);\n\n        [DllImport("kernel32.dll", SetLastError = true)]\n        private static extern bool ReadFile(\n            IntPtr hFile,                        // handle to file\n            byte[] lpBuffer,                // data buffer\n            int nNumberOfBytesToRead,        // number of bytes to read\n            ref int lpNumberOfBytesRead,    // number of bytes read\n            IntPtr lpOverlapped\n            //\n            // ref OVERLAPPED lpOverlapped        // overlapped buffer\n            );\n\n        private SafeFileHandle handleValue = null;\n        private FileStream _fs = null;\n\n        public DeviceStream(string device)\n        {\n            Load(device);\n        }\n\n        private void Load(string Path)\n        {\n            if (string.IsNullOrEmpty(Path))\n            {\n                throw new ArgumentNullException("Path");\n            }\n\n            // Try to open the file.\n            IntPtr ptr = CreateFile(Path, GENERIC_READ, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);\n\n            handleValue = new SafeFileHandle(ptr, true);\n            _fs = new FileStream(handleValue, FileAccess.Read);\n\n            // If the handle is invalid,\n            // get the last Win32 error \n            // and throw a Win32Exception.\n            if (handleValue.IsInvalid)\n            {\n                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());\n            }\n        }\n\n        public override bool CanRead\n        {\n            get { return true; }\n        }\n\n        public override bool CanSeek\n        {\n            get { return false; }\n        }\n\n        public override bool CanWrite\n        {\n            get { return false; }\n        }\n\n        public override void Flush()\n        {\n            return;\n        }\n\n        public override long Length\n        {\n            get { return -1; }\n        }\n\n        public override long Position\n        {\n            get\n            {\n                throw new NotImplementedException();\n            }\n            set\n            {\n                throw new NotImplementedException();\n            }\n        }\n        /// &lt;summary&gt;\n        /// &lt;/summary&gt;\n        /// &lt;param name="buffer"&gt;An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and \n        /// (offset + count - 1) replaced by the bytes read from the current source. &lt;/param&gt;\n        /// &lt;param name="offset"&gt;The zero-based byte offset in buffer at which to begin storing the data read from the current stream. &lt;/param&gt;\n        /// &lt;param name="count"&gt;The maximum number of bytes to be read from the current stream.&lt;/param&gt;\n        /// &lt;returns&gt;&lt;/returns&gt;\n        public override int Read(byte[] buffer, int offset, int count)\n        {\n            int BytesRead =0;\n            var BufBytes = new byte[count];\n            if (!ReadFile(handleValue.DangerousGetHandle(), BufBytes, count, ref BytesRead, IntPtr.Zero))\n            {\n                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());\n            }\n            for (int i = 0; i &lt; BytesRead; i++)\n            {\n                buffer[offset + i] = BufBytes[i];\n            }\n            return BytesRead;\n        }\n        public override int ReadByte()\n        {\n            int BytesRead = 0;\n            var lpBuffer = new byte[1];\n            if (!ReadFile(\n            handleValue.DangerousGetHandle(),                        // handle to file\n            lpBuffer,                // data buffer\n            1,        // number of bytes to read\n            ref BytesRead,    // number of bytes read\n            IntPtr.Zero\n            ))\n            { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); ;}\n            return lpBuffer[0];\n        }\n\n        public override long Seek(long offset, SeekOrigin origin)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override void SetLength(long value)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override void Write(byte[] buffer, int offset, int count)\n        {\n            throw new NotImplementedException();\n        }\n\n        public override void Close()\n        {\n            handleValue.Close();\n            handleValue.Dispose();\n            handleValue = null;\n            base.Close();\n        }\n        private bool disposed = false;\n\n        new void Dispose()\n        {\n            Dispose(true);\n            base.Dispose();\n            GC.SuppressFinalize(this);\n        }\n\n        private new void Dispose(bool disposing)\n        {\n            // Check to see if Dispose has already been called.\n            if (!this.disposed)\n            {\n                if (disposing)\n                {\n                    if (handleValue != null)\n                    {\n                        _fs.Dispose();\n                        handleValue.Close();\n                        handleValue.Dispose();\n                        handleValue = null;\n                    }\n                }\n                // Note disposing has been done.\n                disposed = true;\n\n            }\n        }\n\n    }\n}\n</code></pre>\n\n<p>And an example of using the class</p>\n\n<pre><code>static void Main(string[] args)\n        {\n            var reader = new BinaryReader(new DeviceStream(@"\\\\.\\PhysicalDrive3"));\n            var writer = new BinaryWriter(new FileStream(@"g:\\test.dat", FileMode.Create));\n            var buffer = new byte[MB];\n            int count;\n            int loopcount=0;\n            try{\n                while((count=reader.Read(buffer,0,MB))&gt;0)\n                {\n                    writer.Write(buffer,0,count);\n                    System.Console.Write(\'.\');\n                    if(loopcount%100==0)\n                    {\n                        System.Console.WriteLine();\n                        System.Console.WriteLine("100MB written");\n                        writer.Flush();\n                    }\n                    loopcount++;\n                }\n            }\n            catch(Exception e)\n            {\n                Console.WriteLine(e.Message);\n            }\n            reader.Close();\n            writer.Flush();\n            writer.Close();\n        }\n</code></pre>\n\n<p>Standard disclaimers apply, this code may be hazardous to your health.</p>\n'}, {'answer_id': 26796350, 'author': 'robbie fan', 'author_id': 3231323, 'author_profile': 'https://Stackoverflow.com/users/3231323', 'pm_score': 0, 'selected': False, 'text': '<p>Agree with Mark\'s answer. Note that if User Account Control is enabled (which is the default on Windows Vista and higher), your program must be running elevated (with Administrative privileges). If your program is just used for only a few users, you can request the user to right-click the executable files and choose "Run as Administrator". Otherwise, you can compile a manifest file into the program, and in the manifest, specify that the program needs to be run elevated (search for "requestedExecutionLevel requireAdministrator" to get more information).</p>\n'}, {'answer_id': 67999566, 'author': 'OZone', 'author_id': 8989752, 'author_profile': 'https://Stackoverflow.com/users/8989752', 'pm_score': -1, 'selected': False, 'text': '<p>In .NET 5, you can use the FileStream method to read a file on the disk.</p>\n<pre><code>new FileStream(@&quot;\\\\.\\PhysicalDrive1&quot;, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/38190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1834/']