gpt4 book ai didi

c# - DiscUtils 创建 NTFS vhd

转载 作者:行者123 更新时间:2023-12-03 07:48:25 30 4
gpt4 key购买 nike

我正在尝试在.NET Core 中使用 NTFS 创建虚拟硬盘。

我在其 GitHub page 上找到了 DiscUtils NuGet 包和示例代码可以很好地创建 FAT 格式的 VHD。

long diskSize = 30 * 1024 * 1024; //30MB
using (Stream vhdStream = File.Create(@"C:\TEMP\mydisk.vhd"))
{
Disk disk = Disk.InitializeDynamic(vhdStream, diskSize);
BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsFat);
using (FatFileSystem fs = FatFileSystem.FormatPartition(disk, 0, null))
{
fs.CreateDirectory(@"TestDir\CHILD");
// do other things with the file system...
}
}

但对于我的用例,我需要大于 2 GB 的文件。因为无论如何我们都使用 Windows,所以 NTFS 没问题。所以我尝试了这段代码

long diskSize = 300 * 1024 * 1024; //300 MB
var vhdPath = Path.Combine(Path.GetTempPath(), Path.ChangeExtension(Path.GetRandomFileName(), "vhd"));

using (Stream vhdStream = File.Create(vhdPath))
{
var disk = DiscUtils.Vhd.Disk.InitializeFixed(vhdStream, Ownership.None, diskSize);
BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
using (var ntfs = NtfsFileSystem.Format(vhdStream, "Virtual NTFS drive", Geometry.FromCapacity(diskSize), 0, diskSize / Sizes.Sector))
{
ntfs.CreateDirectory(@"TestDir\CHILD");

// do other things with the file system...
}
}

此代码创建了一个 300 MB 的 VHD,我可以使用 7zip 打开该 VHD,但它包含一个约 300 MB 的 *.mbr 文件。如果我尝试打开它,它会在临时文件夹中打开一个新的 7zip 窗口。如果我对该 vhd 加倍时钟,则会出现 Windows 错误“驱动器镜像未初始化,包含无法识别的分区或包含未分配驱动器号的卷。使用驱动器管理管理单元确保驱动器、分区和卷处于可用状态。”(免费翻译自德语)

此后我无法再访问该文件,因为某些 Windows 进程仍然保持忙碌状态。

我在这里误解了什么?

还有其他方法可以使用 C# 和 .NET Core 创建/挂载 VHD吗?

最佳答案

我从 EricZimmerman 那里得到了有关项目的答案 GitHub page :

var diskSize = 2000 * 1024 * 1024;
var asVhd = false;

using (var fs = new FileStream(_vhfxFileName, FileMode.OpenOrCreate))
{
VirtualDisk destDisk = Disk.InitializeDynamic(fs, Ownership.None, diskSize);

if (asVhd)
{
destDisk = DiscUtils.Vhd.Disk.InitializeDynamic(fs, Ownership.None, diskSize);
}

BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs);
var volMgr = new VolumeManager(destDisk);

var label = $"ZZZZZZ ({dateStamp})";

using (var destNtfs = NtfsFileSystem.Format(volMgr.GetLogicalVolumes()[0], label, new NtfsFormatOptions()))
{
destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;

var destDirectory = Path.GetDirectoryName(@"Some file");
destNtfs.CreateDirectory(destDirectory, nfo);

using (Stream source = new FileStream(@"Some file2", FileMode.Open, FileAccess.Read))
{
var destFileName = @"foo";

using (Stream dest = destNtfs.OpenFile(destFileName, FileMode.Create, FileAccess.ReadWrite))
{
source.CopyTo(dest);
dest.Flush();
}
}
// do more stuff here
}

// commit everything to the stream before closing
fs.Flush();
}

对我有用!享受吧:)

关于c# - DiscUtils 创建 NTFS vhd,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54762062/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com