dahall / Vanara

A set of .NET libraries for Windows implementing PInvoke calls to many native Windows APIs with supporting wrappers.
MIT License
1.79k stars 193 forks source link

Can't use the handle to read vhdx #418

Closed quintushr closed 1 year ago

quintushr commented 1 year ago

I'm sorry, but I don't understand something in Vanara.IO.VirtualDisk.

I'm trying to obtain the handle to read data from a disk file :


var sourceDisk = VirtualDisk.Open(path, false);
sourceDisk.Attach();

// Source Handle 
var sourceFileHandle = new SafeFileHandle(sourceDisk.DangerousGetHandle(), false);
using var sourceFileStream = new FileStream(sourceFileHandle, FileAccess.ReadWrite);

var bufferSize = 1024 * 1024;
var bytesRead = -1;
var bytes = new byte[bufferSize];

var bytesRead = sourceFileStream.Read(bytes, 0, bufferSize)

I encountered an exception on the read line: The device does not recognize the command.

I have conducted extensive research, but I still can't comprehend the issue. I believe it's a genuine problem, but I'm struggling to grasp the exact cause.

dahall commented 1 year ago

A virtual disk represents an entire file system, not a single file. If you want to read the raw bits of the file, then just read the file (path in your example) directly using System.IO functions. If you are trying to see files within the virtual disk, then you need to attach it to a volume (your code has the system not assigning a drive letter) and then acting on that volume like a local disk.

sourceDisk.Attach(new[] { "T:\\" }, true, true);
foreach (var d in System.IO.Directory.EnumerateFiles("T:\\"))
   Console.WriteLine(d.FullPath);
quintushr commented 1 year ago

Thanks !