### Initialize GPT Partition Table Source: https://context7.com/ltrdata/discutils/llms.txt Initializes a GUID Partition Table (GPT) on a disk and creates typed partitions. ```APIDOC ## GuidPartitionTable.Initialize — Create a GPT partition table Initializes a GUID Partition Table (GPT) on a disk and creates typed partitions. ### Method - `GuidPartitionTable.Initialize(DiscUtils.Disk disk)` ### Parameters - **disk** (DiscUtils.Disk) - The virtual disk to initialize. ### Usage ```csharp using DiscUtils; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhdx; using System.IO; using var disk = Disk.Initialize(new MemoryStream(), Ownership.Dispose, 64L * 1024 * 1024 * 1024); var gpt = GuidPartitionTable.Initialize(disk); // Create an EFI System Partition and a basic data partition gpt.Create(256 * 1024 * 1024 / 512, GuidPartitionTypes.EfiSystemPartition, "EFI System", 0); gpt.Create(gpt.LastUsableSector - gpt.FirstUsableSector - (256 * 1024 * 1024 / 512), GuidPartitionTypes.WindowsBasicData, "Data", 0); Console.WriteLine($"GPT disk GUID: {gpt.DiskGuid}"); foreach (var part in gpt.Partitions) Console.WriteLine($" {part.TypeGuid} {part.FirstSector}-{part.LastSector}"); ``` ``` -------------------------------- ### Initialize GPT Partition Table Source: https://context7.com/ltrdata/discutils/llms.txt Demonstrates creating a GUID Partition Table (GPT) on a disk and adding typed partitions. Supports standard partition types like EFI System Partition and Windows Basic Data. ```csharp using DiscUtils; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhdx; using System.IO; using var disk = Disk.Initialize(new MemoryStream(), Ownership.Dispose, 64L * 1024 * 1024 * 1024); var gpt = GuidPartitionTable.Initialize(disk); // Create an EFI System Partition and a basic data partition gpt.Create(256 * 1024 * 1024 / 512, GuidPartitionTypes.EfiSystemPartition, "EFI System", 0); gpt.Create(gpt.LastUsableSector - gpt.FirstUsableSector - (256 * 1024 * 1024 / 512), GuidPartitionTypes.WindowsBasicData, "Data", 0); Console.WriteLine($"GPT disk GUID: {gpt.DiskGuid}"); foreach (var part in gpt.Partitions) Console.WriteLine($" {part.TypeGuid} {part.FirstSector}–{part.LastSector}"); ``` -------------------------------- ### Format FAT Partition Source: https://context7.com/ltrdata/discutils/llms.txt Provides an example of formatting an existing partition within a virtual disk with FAT12, FAT16, or FAT32. Allows setting a volume label and creating directories and files. ```csharp using DiscUtils; using DiscUtils.Fat; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; using var disk = Disk.InitializeDynamic(new MemoryStream(), Ownership.Dispose, 16 * 1024 * 1024); BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsFat); using var fs = FatFileSystem.FormatPartition(disk, partitionIndex: 0, label: "MYDATA"); fs.CreateDirectory(@"Documents\Reports"); using (var file = fs.OpenFile(@"Documents\Reports\hello.txt", FileMode.Create, FileAccess.Write)) using (var writer = new System.IO.StreamWriter(file)) writer.WriteLine("Hello from DiscUtils FAT!"); Console.WriteLine($"FAT type: {fs.FatVariant}"); Console.WriteLine($"Volume label: {fs.VolumeLabel}"); Console.WriteLine($"Free space: {fs.AvailableSpace} bytes"); ``` -------------------------------- ### Register DiscUtils Assemblies Source: https://github.com/ltrdata/discutils/blob/LTRData.DiscUtils-initial/README.md Register DiscUtils filesystem providers by calling RegisterAssembly. Metapackages provide helper methods for common setups. ```csharp DiscUtils.Setup.RegisterAssembly(assembly); ``` ```csharp SetupHelper.SetupComplete(); // From DiscUtils.Complete SetupHelper.SetupContainers(); // From DiscUtils.Containers SetupHelper.SetupFileSystems(); // From DiscUtils.FileSystems SetupHelper.SetupTransports(); // From DiscUtils.Transports ``` -------------------------------- ### Extract a File from an ISO Source: https://github.com/ltrdata/discutils/blob/LTRData.DiscUtils-initial/README.md Opens an ISO file, reads a specific file from it, and provides a Stream to access the file's content. The directory hierarchy can be browsed starting from cd.Root. ```csharp using (FileStream isoStream = File.Open(@"C:\temp\sample.iso")) { CDReader cd = new CDReader(isoStream, true); Stream fileStream = cd.OpenFile(@"Folder\Hello.txt", FileMode.Open); // Use fileStream... } ``` -------------------------------- ### SetupHelper.SetupComplete Source: https://context7.com/ltrdata/discutils/llms.txt Registers all built-in format assemblies for DiscUtils. This should be called once at application startup to enable auto-detection of file systems and virtual disk types. ```APIDOC ## SetupHelper.SetupComplete — Register all built-in format assemblies ### Description Call this once at application startup (using the `DiscUtils.Complete` meta-package) to register every bundled file system and virtual disk type so that auto-detection works. ### Method `SetupHelper.SetupComplete()` ### Code Example ```csharp using DiscUtils.Complete; // Register every bundled filesystem and disk type (call once at startup) SetupHelper.SetupComplete(); // Alternatively, register individual assemblies: // DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Ntfs.NtfsFileSystem).Assembly); // DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Vhd.Disk).Assembly); ``` ``` -------------------------------- ### Create a Virtual Hard Disk (VHD) Source: https://github.com/ltrdata/discutils/blob/LTRData.DiscUtils-initial/README.md Initializes a new dynamic virtual hard disk (VHD) of a specified size, sets up a BIOS partition table, and formats a partition with a FAT file system. The file system can then be used to create directories and files. ```csharp 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... } } ``` -------------------------------- ### Initialize MBR Partition Table Source: https://context7.com/ltrdata/discutils/llms.txt Shows how to create a new BIOS/MBR partition table on a virtual disk. Partitions can be initialized with well-known types or created manually with specified sizes. ```csharp using DiscUtils; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; using var disk = Disk.InitializeDynamic(new MemoryStream(), Ownership.Dispose, 30L * 1024 * 1024); // Initialize MBR with a single Windows FAT partition BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsFat); // Or create multiple partitions manually var pt = BiosPartitionTable.Initialize(disk); int idx0 = pt.Create(15 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); int idx1 = pt.Create(5 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); Console.WriteLine($"Partition count: {pt.Count}"); Console.WriteLine($"Partition 0 size: {pt.Partitions[idx0].SectorCount * 512} bytes"); // Delete a partition pt.Delete(idx1); ``` -------------------------------- ### Initialize VHD Disks Source: https://context7.com/ltrdata/discutils/llms.txt Demonstrates creating dynamic, fixed, and differencing VHD disk images directly into streams. ```APIDOC ## Vhd.Disk.InitializeDynamic / InitializeFixed — Create VHD disks in a stream Creates VHD disk images directly into any writable `Stream`, useful for in-memory or embedded disks. ### Method - `Disk.InitializeDynamic(Stream stream, Ownership ownership, long size)` - `Disk.InitializeFixed(Stream stream, Ownership ownership, long size)` - `Disk.InitializeDifferencing(Stream stream, Ownership streamOwnership, DiskImageFile baseDisk, Ownership baseDiskOwnership, string basePath, string diffPath, DateTime timestamp)` ### Parameters #### InitializeDynamic/InitializeFixed - **stream** (Stream) - The writable stream to create the VHD in. - **ownership** (Ownership) - Controls whether the stream is disposed when the disk is disposed. - **size** (long) - The virtual size of the disk in bytes. #### InitializeDifferencing - **stream** (Stream) - The writable stream to create the differencing disk in. - **streamOwnership** (Ownership) - Controls whether the stream is disposed when the disk is disposed. - **baseDisk** (DiskImageFile) - The base disk image. - **baseDiskOwnership** (Ownership) - Controls whether the base disk is disposed when the differencing disk is disposed. - **basePath** (string) - Path to the base disk. - **diffPath** (string) - Path to the differencing disk. - **timestamp** (DateTime) - The timestamp for the differencing disk. ### Request Example ```csharp // Dynamic VHD (sparse — only allocates space for written sectors) var ms = new MemoryStream(); using (var disk = DiscUtils.Vhd.Disk.InitializeDynamic(ms, Ownership.None, 16L * 1024 * 1024 * 1024)) { Console.WriteLine($"Dynamic VHD geometry: {disk.Geometry}"); Console.WriteLine($"Stream size: {ms.Length} bytes (much less than 16 GB)"); } // Fixed VHD (pre-allocates all space) var fixedMs = new MemoryStream(); using var fixedDisk = DiscUtils.Vhd.Disk.InitializeFixed(fixedMs, Ownership.None, 8 * 1024 * 1024); Console.WriteLine($"Fixed VHD capacity: {fixedDisk.Capacity / 1024 / 1024} MB"); // Differencing VHD (copy-on-write child referencing a base disk) var baseStream = new MemoryStream(); var diffStream = new MemoryStream(); var baseFile = DiscUtils.Vhd.DiskImageFile.InitializeDynamic(baseStream, Ownership.Dispose, 16L * 1024 * 1024 * 1024); using var diffDisk = DiscUtils.Vhd.Disk.InitializeDifferencing( diffStream, Ownership.None, baseFile, Ownership.Dispose, @"C:\TEMP\Base.vhd", @".\Base.vhd", DateTime.UtcNow); Console.WriteLine($"Diff disk layers: {diffDisk.Layers.Count()}"); ``` ``` -------------------------------- ### Create New Virtual Disk Source: https://context7.com/ltrdata/discutils/llms.txt Creates a new virtual disk of a specified type and variant at a given path with a defined capacity. Ensure SetupComplete() is called prior to use. ```csharp using DiscUtils; using DiscUtils.Complete; using System.IO; SetupHelper.SetupComplete(); long capacityBytes = 40L * 1024 * 1024 * 1024; // 40 GB // Create a dynamic VHD using VirtualDisk vhd = VirtualDisk.CreateDisk( type: "VHD", variant: "dynamic", path: @"C:\\Images\\new.vhd", capacity: capacityBytes, geometry: null, parameters: null) ?? throw new InvalidOperationException("Failed to create disk"); Console.WriteLine($"Created dynamic VHD, capacity = {vhd.Capacity} bytes"); // Create a fixed VMDK using VirtualDisk vmdk = VirtualDisk.CreateDisk( type: "VMDK", variant: "fixed", path: @"C:\\Images\\new.vmdk", capacity: 8L * 1024 * 1024 * 1024, geometry: null, parameters: null)!; ``` -------------------------------- ### Initialize MBR Partition Table Source: https://context7.com/ltrdata/discutils/llms.txt Creates a new BIOS/MBR partition table on a virtual disk and optionally creates partitions. ```APIDOC ## BiosPartitionTable.Initialize — Create an MBR partition table Initializes a new BIOS/MBR partition table on a virtual disk and creates partitions. ### Method - `BiosPartitionTable.Initialize(DiscUtils.Disk disk, WellKnownPartitionType partitionType)` - `BiosPartitionTable.Initialize(DiscUtils.Disk disk)` ### Parameters - **disk** (DiscUtils.Disk) - The virtual disk to initialize. - **partitionType** (WellKnownPartitionType, optional) - The type of the single partition to create. ### Usage ```csharp using DiscUtils; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; using var disk = Disk.InitializeDynamic(new MemoryStream(), Ownership.Dispose, 30L * 1024 * 1024); // Initialize MBR with a single Windows FAT partition BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsFat); // Or create multiple partitions manually var pt = BiosPartitionTable.Initialize(disk); int idx0 = pt.Create(15 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); int idx1 = pt.Create(5 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); Console.WriteLine($"Partition count: {pt.Count}"); Console.WriteLine($"Partition 0 size: {pt.Partitions[idx0].SectorCount * 512} bytes"); // Delete a partition pt.Delete(idx1); ``` ``` -------------------------------- ### Create Differencing Disk with DiscUtils Source: https://context7.com/ltrdata/discutils/llms.txt Creates a differencing disk (snapshot) that stores deltas from a parent disk. Ensure the parent disk is properly initialized and populated before creating the differencing disk. ```csharp using DiscUtils; using DiscUtils.Complete; using DiscUtils.Ntfs; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; SetupHelper.SetupComplete(); // 1. Create and populate a base VHD using var baseStream = File.Create(@"C:\Images\base.vhd"); using (var baseDisk = Disk.InitializeDynamic(baseStream, Ownership.None, 4L * 1024 * 1024 * 1024)) { BiosPartitionTable.Initialize(baseDisk, WellKnownPartitionType.WindowsNtfs); using var ntfs = NtfsFileSystem.Format( baseDisk.Partitions![0].Open(), "BASE", baseDisk.Geometry!.Value, baseDisk.Partitions[0].FirstSector, baseDisk.Partitions[0].SectorCount); ntfs.WriteAllBytes("readme.txt", System.Text.Encoding.UTF8.GetBytes("base content")); } // 2. Open base read-only; create differencing disk on top using var parentDisk = new Disk(@"C:\Images\base.vhd", FileAccess.Read); using var diffDisk = parentDisk.CreateDifferencingDisk(@"C:\Images\diff.vhd"); Console.WriteLine($"Diff disk layers: {diffDisk.Layers.Count()}"); Console.WriteLine($"Diff disk capacity: {diffDisk.Capacity} bytes"); ``` -------------------------------- ### Common file system operations with DiscFileSystem Source: https://context7.com/ltrdata/discutils/llms.txt This snippet demonstrates common file and directory operations that work across different DiscUtils file system implementations like NTFS, FAT, and Ext. Ensure you have an instance of a DiscFileSystem implementation. ```csharp using DiscUtils; using DiscUtils.Ntfs; using System.IO; // Works identically for NtfsFileSystem, FatFileSystem, ExtFileSystem, etc. DiscFileSystem fs = /* any DiscFileSystem instance */ new NtfsFileSystem(stream); // Directory operations fs.CreateDirectory(@"Dir\SubDir"); fs.MoveDirectory(@"Dir\SubDir", @"Dir\Renamed"); bool exists = fs.DirectoryExists(@"Dir\Renamed"); // true // File operations fs.WriteAllBytes(@"Dir\data.bin", new byte[] { 1, 2, 3, 4 }); byte[] data = fs.ReadAllBytes(@"Dir\data.bin"); // Open file as stream (read/write/create) using (var stream = fs.OpenFile(@"Dir\log.txt", FileMode.Create, FileAccess.Write)) using (var writer = new System.IO.StreamWriter(stream)) writer.WriteLine("log entry"); // Enumerate foreach (string dir in fs.GetDirectories("", "*", SearchOption.AllDirectories)) Console.WriteLine($"DIR {dir}"); foreach (string file in fs.GetFiles("", "*.*", SearchOption.AllDirectories)) Console.WriteLine($"FILE {file}"); // Metadata fs.SetAttributes(@"Dir\data.bin", FileAttributes.Hidden | FileAttributes.ReadOnly); fs.SetCreationTimeUtc(@"Dir\data.bin", DateTime.UtcNow); long len = fs.GetFileLength(@"Dir\data.bin"); // Space Console.WriteLine($"Total: {fs.Size}, Used: {fs.UsedSpace}, Free: {fs.AvailableSpace}"); ``` -------------------------------- ### Create Dynamic, Fixed, and Differencing VHDs Source: https://context7.com/ltrdata/discutils/llms.txt Demonstrates creating VHD disk images directly into memory streams. Use dynamic VHDs for sparse allocation and fixed VHDs for pre-allocated space. Differencing VHDs are useful for copy-on-write scenarios. ```csharp using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; // Dynamic VHD (sparse — only allocates space for written sectors) var ms = new MemoryStream(); using (var disk = Disk.InitializeDynamic(ms, Ownership.None, 16L * 1024 * 1024 * 1024)) { Console.WriteLine($"Dynamic VHD geometry: {disk.Geometry}"); Console.WriteLine($"Stream size: {ms.Length} bytes (much less than 16 GB)"); } // Fixed VHD (pre-allocates all space) var fixedMs = new MemoryStream(); using var fixedDisk = Disk.InitializeFixed(fixedMs, Ownership.None, 8 * 1024 * 1024); Console.WriteLine($"Fixed VHD capacity: {fixedDisk.Capacity / 1024 / 1024} MB"); // Differencing VHD (copy-on-write child referencing a base disk) var baseStream = new MemoryStream(); var diffStream = new MemoryStream(); var baseFile = DiskImageFile.InitializeDynamic(baseStream, Ownership.Dispose, 16L * 1024 * 1024 * 1024); using var diffDisk = Disk.InitializeDifferencing( diffStream, Ownership.None, baseFile, Ownership.Dispose, @"C:\\TEMP\\Base.vhd", @".\\Base.vhd", DateTime.UtcNow); Console.WriteLine($"Diff disk layers: {diffDisk.Layers.Count()}"); ``` -------------------------------- ### Build ISO 9660 Disc Image with CDBuilder Source: https://context7.com/ltrdata/discutils/llms.txt Constructs ISO images with optional Joliet and boot catalog support from in-memory data, file paths, or streams. Ensure necessary using statements are included. ```csharp using DiscUtils.Iso9660; using System.IO; using System.Text; var builder = new CDBuilder { VolumeIdentifier = "MYINSTALL", UseJoliet = true, UpdateIsolinuxBootTable = false }; // Add files from byte arrays, disk paths, or streams builder.AddFile(@"README.TXT", Encoding.ASCII.GetBytes("Welcome to MyInstall!\n")); builder.AddFile(@"Setup\install.bat", @"C:\src\install.bat"); builder.AddDirectory(@"Data\Logs"); // Optional boot image // builder.SetBootImage(File.OpenRead("boot.img"), BootDeviceEmulation.NoEmulation, 0); // Build to file builder.Build(@"C:\Output\myinstall.iso"); // Or build to a stream var isoStream = new MemoryStream(); builder.Build(isoStream); // Read back isoStream.Position = 0; using var reader = new CDReader(isoStream, joliet: true) { Console.WriteLine($"Volume: {reader.VolumeLabel}"); foreach (var f in reader.GetFiles("", "*.*", SearchOption.AllDirectories)) Console.WriteLine(f); } ``` -------------------------------- ### Register All DiscUtils Assemblies Source: https://context7.com/ltrdata/discutils/llms.txt Call this once at application startup to enable auto-detection of all bundled file system and virtual disk types. Alternatively, individual assemblies can be registered. ```csharp using DiscUtils.Complete; // Register every bundled filesystem and disk type (call once at startup) SetupHelper.SetupComplete(); // Alternatively, register individual assemblies: // DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Ntfs.NtfsFileSystem).Assembly); // DiscUtils.Setup.SetupHelper.RegisterAssembly(typeof(DiscUtils.Vhd.Disk).Assembly); ``` -------------------------------- ### Create a New ISO File Source: https://github.com/ltrdata/discutils/blob/LTRData.DiscUtils-initial/README.md Creates a new ISO file with specified volume identifier and adds a file. The ISO can be built to a file path or a Stream. ```csharp CDBuilder builder = new CDBuilder(); builder.UseJoliet = true; builder.VolumeIdentifier = "A_SAMPLE_DISK"; builder.AddFile(@"Folder\Hello.txt", Encoding.ASCII.GetBytes("Hello World!")); builder.Build(@"C:\temp\sample.iso"); ``` -------------------------------- ### Format a stream with NTFS using NtfsFileSystem.Format Source: https://context7.com/ltrdata/discutils/llms.txt Use this to create a new NTFS volume on a writable stream or virtual disk partition. Ensure necessary using statements are included. The volume can be labeled and configured with disk geometry. ```csharp using DiscUtils; using DiscUtils.Ntfs; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; using var disk = Disk.InitializeDynamic(new MemoryStream(), Ownership.Dispose, 4L * 1024 * 1024 * 1024); BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs); using var partStream = disk.Partitions![0].Open(); using var ntfs = NtfsFileSystem.Format( partStream, label: "MyVolume", diskGeometry: disk.Geometry ?? disk.BiosGeometry, firstSector: disk.Partitions[0].FirstSector, sectorCount: disk.Partitions[0].SectorCount); ntfs.CreateDirectory(@"Users\Alice"); using (var file = ntfs.OpenFile(@"Users\Alice\notes.txt", FileMode.Create, FileAccess.Write)) using (var w = new System.IO.StreamWriter(file)) w.WriteLine("NTFS via DiscUtils"); // NTFS-specific: set security descriptor var sd = new DiscUtils.Core.WindowsSecurity.AccessControl.RawSecurityDescriptor( "O:BAG:BAD:(A;OICINP;GA;;;BA)"); ntfs.CreateDirectory("secure"); ntfs.SetSecurity("secure", sd); Console.WriteLine($"NTFS used space: {ntfs.UsedSpace / 1024} KB"); ``` -------------------------------- ### CDBuilder Source: https://context7.com/ltrdata/discutils/llms.txt Constructs ISO 9660 disc images with optional Joliet and boot catalog support from in-memory data, file paths, or streams. ```APIDOC ## CDBuilder — Build ISO 9660 disc images Constructs ISO images (with optional Joliet and boot catalog support) from in-memory data, file paths, or streams. ### Usage ```csharp var builder = new CDBuilder { VolumeIdentifier = "MYINSTALL", UseJoliet = true, UpdateIsolinuxBootTable = false }; // Add files from byte arrays, disk paths, or streams builder.AddFile(@"README.TXT", Encoding.ASCII.GetBytes("Welcome to MyInstall!\n")); builder.AddFile(@"Setup\install.bat", @"C:\src\install.bat"); builder.AddDirectory(@"Data\Logs"); // Optional boot image // builder.SetBootImage(File.OpenRead("boot.img"), BootDeviceEmulation.NoEmulation, 0); // Build to file builder.Build(@"C:\Output\myinstall.iso"); // Or build to a stream var isoStream = new MemoryStream(); builder.Build(isoStream); // Read back isoStream.Position = 0; using var reader = new CDReader(isoStream, joliet: true); Console.WriteLine($"Volume: {reader.VolumeLabel}"); foreach (var f in reader.GetFiles("", "*.*", SearchOption.AllDirectories)) Console.WriteLine(f); ``` ``` -------------------------------- ### Open Virtual Disk (Auto-Detect) Source: https://context7.com/ltrdata/discutils/llms.txt Opens a virtual disk file, automatically detecting its format from the file extension. Supports various formats including VHD, VHDX, VMDK, and ISO. Ensure SetupComplete() is called first. ```csharp using DiscUtils; using DiscUtils.Complete; using System.IO; SetupHelper.SetupComplete(); // Open read-only; format detected from ".vhd" extension using VirtualDisk disk = VirtualDisk.OpenDisk(@"C:\\Images\\system.vhd", FileAccess.Read) ?? throw new FileNotFoundException("Could not open disk"); Console.WriteLine($"Disk type : {disk.DiskTypeInfo.Name}"); Console.WriteLine($"Capacity : {disk.Capacity / (1024 * 1024 * 1024.0):F1} GB"); Console.WriteLine($"Partitioned: {disk.IsPartitioned}"); // Force a specific type (e.g. RAW) regardless of extension using VirtualDisk raw = VirtualDisk.OpenDisk("disk.img", "RAW", FileAccess.ReadWrite, null, null) ?? throw new FileNotFoundException(); ``` -------------------------------- ### WimFile and WimFileSystem Source: https://context7.com/ltrdata/discutils/llms.txt Reads WIM files and exposes each contained disk image as a DiscFileSystem. ```APIDOC ## WimFile and WimFileSystem — Windows Imaging (WIM) file access Reads WIM files and exposes each contained disk image as a `DiscFileSystem`. ### Usage ```csharp using var wimStream = File.OpenRead(@"C:\Sources\install.wim"); var wim = new WimFile(wimStream); Console.WriteLine($"Images in WIM : {wim.ImageCount}"); Console.WriteLine($"Boot image : {wim.BootImage}"); // Access a specific image (zero-based index) using var fs = wim.GetImage(0); Console.WriteLine($"Volume label: {fs.VolumeLabel}"); // List files foreach (var path in fs.GetFiles(@"Windows\System32", "*.dll", SearchOption.TopDirectoryOnly)) Console.WriteLine(path); // Extract a file using var src = fs.OpenFile(@"Windows\System32\ntdll.dll", FileMode.Open, FileAccess.Read); using var dst = File.Create(@"C:\Extracted\ntdll.dll"); src.CopyTo(dst); ``` ``` -------------------------------- ### Create a Virtual Floppy Disk (VFD) Source: https://github.com/ltrdata/discutils/blob/LTRData.DiscUtils-initial/README.md Creates a virtual floppy disk image and formats it with a FAT file system. A file can be created within the floppy disk's file system using a Stream. ```csharp using (FileStream fs = File.Create(@"myfloppy.vfd")) { using (FatFileSystem floppy = FatFileSystem.FormatFloppy(fs, FloppyDiskType.HighDensity, "MY FLOPPY ")) { using (Stream s = floppy.OpenFile("foo.txt", FileMode.Create)) { // Use stream... } } } ``` -------------------------------- ### VirtualDisk.CreateDifferencingDisk Source: https://context7.com/ltrdata/discutils/llms.txt Creates a copy-on-write child disk that stores only deltas from a parent, enabling non-destructive experiments. ```APIDOC ## VirtualDisk.CreateDifferencingDisk ### Description Creates a copy-on-write child disk that stores only deltas from a parent, enabling non-destructive experiments. ### Method C# ### Endpoint N/A (Method call) ### Parameters None explicitly documented for the method call itself, but requires a parent disk to be opened. ### Request Example ```csharp using DiscUtils; using DiscUtils.Complete; using DiscUtils.Ntfs; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; // Assume SetupHelper.SetupComplete() has been called. // 1. Create and populate a base VHD using var baseStream = File.Create(@"C:\Images\base.vhd"); using (var baseDisk = Disk.InitializeDynamic(baseStream, Ownership.None, 4L * 1024 * 1024 * 1024)) { BiosPartitionTable.Initialize(baseDisk, WellKnownPartitionType.WindowsNtfs); using var ntfs = NtfsFileSystem.Format( baseDisk.Partitions![0].Open(), "BASE", baseDisk.Geometry!.Value, baseDisk.Partitions[0].FirstSector, baseDisk.Partitions[0].SectorCount); ntfs.WriteAllBytes("readme.txt", System.Text.Encoding.UTF8.GetBytes("base content")); } // 2. Open base read-only; create differencing disk on top using var parentDisk = new Disk(@"C:\Images\base.vhd", FileAccess.Read); using var diffDisk = parentDisk.CreateDifferencingDisk(@"C:\Images\diff.vhd"); Console.WriteLine($"Diff disk layers: {diffDisk.Layers.Count()}"); Console.WriteLine($"Diff disk capacity: {diffDisk.Capacity} bytes"); ``` ### Response Returns a new `VirtualDisk` object representing the differencing disk. ``` -------------------------------- ### VirtualDisk.AsSynchronized Source: https://context7.com/ltrdata/discutils/llms.txt Wraps a `VirtualDisk` in a synchronized wrapper for safe concurrent access from multiple threads. ```APIDOC ## VirtualDisk.AsSynchronized ### Description Wraps a `VirtualDisk` in a synchronized wrapper for safe concurrent access from multiple threads. ### Method C# ### Endpoint N/A (Method call) ### Parameters - **ownership**: `DiscUtils.Ownership` - Specifies whether the wrapper owns the underlying disk. ### Request Example ```csharp using DiscUtils; using DiscUtils.Complete; using DiscUtils.Streams; using System.IO; using System.Threading.Tasks; // Assume SetupHelper.SetupComplete() has been called. using var disk = VirtualDisk.OpenDisk(@"C:\Images\shared.vhd", FileAccess.Read)!; using var syncDisk = disk.AsSynchronized(Ownership.None); // Multiple threads can now safely read from syncDisk await Task.WhenAll( Task.Run(() => { var mbr = syncDisk.GetMasterBootRecord(); Console.WriteLine($"Thread 1 MBR sig: 0x{syncDisk.Signature:X8}"); }), Task.Run(() => { Console.WriteLine($"Thread 2 capacity: {syncDisk.Capacity}"); }) ); ``` ### Response Returns a synchronized `VirtualDisk` wrapper. ``` -------------------------------- ### FileSystemManager.DetectFileSystems Source: https://context7.com/ltrdata/discutils/llms.txt Inspects a stream or volume to automatically detect and identify file systems present. It returns a list of detected file systems, each with an `Open()` method. ```APIDOC ## FileSystemManager.DetectFileSystems — Auto-detect file systems on a stream or volume Inspects a stream or volume and returns a list of detected file systems with `Open()` methods. ### Parameters - `stream` (Stream): The stream or volume to inspect. ### Returns - `List`: A list of detected file system information objects. ### FileSystemInfo Properties - `Name` (string): The name of the detected file system. - `Open(Stream stream, object[] parameters)`: Method to open the file system on the given stream. ### Example ```csharp using DiscUtils; using System.IO; // Assuming 'partStream' is a readable stream var results = FileSystemManager.DetectFileSystems(partStream); foreach (var info in results) { Console.WriteLine($"Detected: {info.Name}"); using var fs = info.Open(partStream, null); } ``` ``` -------------------------------- ### DiscFileSystem Common Operations Source: https://context7.com/ltrdata/discutils/llms.txt Provides a uniform API for directory and file I/O, metadata management, and traversal across various file system implementations like NTFS, FAT, and Ext. ```APIDOC ## DiscFileSystem (common file system operations) All file system implementations inherit from `DiscFileSystem`, providing a uniform API for directory and file I/O, metadata, and traversal. ### Directory Operations - `CreateDirectory(string path)` - `MoveDirectory(string sourceDirName, string destDirName)` - `DirectoryExists(string path)` ### File Operations - `WriteAllBytes(string path, byte[] data)` - `ReadAllBytes(string path)` - `OpenFile(string path, FileMode mode, FileAccess access)` ### Enumeration - `GetDirectories(string searchPath, string searchPattern, SearchOption searchOption)` - `GetFiles(string searchPath, string searchPattern, SearchOption searchOption)` ### Metadata - `SetAttributes(string path, FileAttributes attributes)` - `SetCreationTimeUtc(string path, DateTime creationTimeUtc)` - `GetFileLength(string path)` ### Space Information - `Size` (long): Total size of the file system. - `UsedSpace` (long): Used space on the file system. - `AvailableSpace` (long): Available space on the file system. ### Example ```csharp using DiscUtils; using System.IO; // Assuming 'fs' is an instance of DiscFileSystem (e.g., NtfsFileSystem) fs.CreateDirectory(@"Dir\SubDir"); fs.WriteAllBytes(@"Dir\data.bin", new byte[] { 1, 2, 3, 4 }); ``` ``` -------------------------------- ### VirtualDisk.CreateDisk Source: https://context7.com/ltrdata/discutils/llms.txt Creates a new virtual disk at a specified path with a given type, variant, and capacity. Supports various disk formats and configurations. ```APIDOC ## VirtualDisk.CreateDisk — Create a new virtual disk ### Description Creates a new virtual disk of a specified type and variant at the given path. ### Method `VirtualDisk.CreateDisk(string type, string variant, string path, long capacity, object geometry, object parameters)` ### Parameters #### Path Parameters - **type** (string) - Required - The format of the virtual disk to create (e.g., "VHD", "VMDK"). - **variant** (string) - Required - The variant of the disk (e.g., "dynamic", "fixed"). - **path** (string) - Required - The path where the new virtual disk file will be created. #### Query Parameters - **capacity** (long) - Required - The desired capacity of the virtual disk in bytes. - **geometry** (object) - Optional - Disk geometry information. - **parameters** (object) - Optional - Additional parameters for disk creation. ### Request Example ```csharp using DiscUtils; using DiscUtils.Complete; using System.IO; SetupHelper.SetupComplete(); long capacityBytes = 40L * 1024 * 1024 * 1024; // 40 GB // Create a dynamic VHD using VirtualDisk vhd = VirtualDisk.CreateDisk( type: "VHD", variant: "dynamic", path: @"C:\Images\new.vhd", capacity: capacityBytes, geometry: null, parameters: null) ?? throw new InvalidOperationException("Failed to create disk"); Console.WriteLine($"Created dynamic VHD, capacity = {vhd.Capacity} bytes"); // Create a fixed VMDK using VirtualDisk vmdk = VirtualDisk.CreateDisk( type: "VMDK", variant: "fixed", path: @"C:\Images\new.vmdk", capacity: 8L * 1024 * 1024 * 1024, geometry: null, parameters: null)!; ``` ### Response #### Success Response (VirtualDisk) - **VirtualDisk** - The newly created virtual disk object. #### Response Example ```json { "VirtualDisk": { "DiskTypeInfo": { "Name": "VHD", "Description": "Microsoft Virtual Hard Disk" }, "Capacity": 42949672960, "IsPartitioned": false } } ``` ``` -------------------------------- ### Access Windows Imaging (WIM) Files Source: https://context7.com/ltrdata/discutils/llms.txt Reads WIM files and exposes each contained disk image as a DiscFileSystem. Ensure the WIM stream and file system are properly disposed. ```csharp using DiscUtils.Wim; using System.IO; using var wimStream = File.OpenRead(@"C:\Sources\install.wim"); var wim = new WimFile(wimStream); Console.WriteLine($"Images in WIM : {wim.ImageCount}"); Console.WriteLine($"Boot image : {wim.BootImage}"); // Access a specific image (zero-based index) using var fs = wim.GetImage(0); Console.WriteLine($"Volume label: {fs.VolumeLabel}"); // List files foreach (var path in fs.GetFiles(@"Windows\System32", "*.dll", SearchOption.TopDirectoryOnly)) Console.WriteLine(path); // Extract a file using var src = fs.OpenFile(@"Windows\System32\ntdll.dll", FileMode.Open, FileAccess.Read); using var dst = File.Create(@"C:\Extracted\ntdll.dll"); src.CopyTo(dst); ``` -------------------------------- ### Format FAT Partition Source: https://context7.com/ltrdata/discutils/llms.txt Formats an existing partition within a virtual disk with FAT12, FAT16, or FAT32. ```APIDOC ## FatFileSystem.FormatPartition — Format a FAT partition Formats an existing partition inside a virtual disk with FAT12/16/32. ### Method - `FatFileSystem.FormatPartition(DiscUtils.Disk disk, int partitionIndex, string label)` ### Parameters - **disk** (DiscUtils.Disk) - The virtual disk containing the partition. - **partitionIndex** (int) - The index of the partition to format. - **label** (string, optional) - The volume label for the formatted partition. ### Usage ```csharp using DiscUtils; using DiscUtils.Fat; using DiscUtils.Partitions; using DiscUtils.Streams; using DiscUtils.Vhd; using System.IO; using var disk = Disk.InitializeDynamic(new MemoryStream(), Ownership.Dispose, 16 * 1024 * 1024); BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsFat); using var fs = FatFileSystem.FormatPartition(disk, partitionIndex: 0, label: "MYDATA"); fs.CreateDirectory(@"Documents\Reports"); using (var file = fs.OpenFile(@"Documents\Reports\hello.txt", FileMode.Create, FileAccess.Write)) using (var writer = new System.IO.StreamWriter(file)) writer.WriteLine("Hello from DiscUtils FAT!"); Console.WriteLine($"FAT type: {fs.FatVariant}"); Console.WriteLine($"Volume label: {fs.VolumeLabel}"); Console.WriteLine($"Free space: {fs.AvailableSpace} bytes"); ``` ``` -------------------------------- ### VirtualDisk.OpenDisk Source: https://context7.com/ltrdata/discutils/llms.txt Opens an existing virtual disk file, automatically detecting its format based on the file extension. It supports various formats including VHD, VHDX, VMDK, VDI, XVA, ISO, and raw images, as well as transport URIs. ```APIDOC ## VirtualDisk.OpenDisk — Open an existing virtual disk ### Description Opens a virtual disk file, auto-detecting its format by file extension. Supports VHD, VHDX, VMDK, VDI, XVA, ISO, and raw images, as well as transport URIs. ### Method `VirtualDisk.OpenDisk(string path, FileAccess access)` `VirtualDisk.OpenDisk(string path, string type, FileAccess access, object[] parameters)` ### Parameters #### Path Parameters - **path** (string) - Required - The path to the virtual disk file or transport URI. - **type** (string) - Optional - The specific disk type to open (e.g., "RAW"). If not provided, the type is auto-detected. #### Query Parameters - **access** (FileAccess) - Required - Specifies the desired access mode (Read, ReadWrite). - **parameters** (object[]) - Optional - Additional parameters for opening the disk. ### Request Example ```csharp using DiscUtils; using DiscUtils.Complete; using System.IO; SetupHelper.SetupComplete(); // Open read-only; format detected from ".vhd" extension using VirtualDisk disk = VirtualDisk.OpenDisk(@"C:\Images\system.vhd", FileAccess.Read) ?? throw new FileNotFoundException("Could not open disk"); Console.WriteLine($"Disk type : {disk.DiskTypeInfo.Name}"); Console.WriteLine($"Capacity : {disk.Capacity / (1024 * 1024 * 1024.0):F1} GB"); Console.WriteLine($"Partitioned: {disk.IsPartitioned}"); // Force a specific type (e.g. RAW) regardless of extension using VirtualDisk raw = VirtualDisk.OpenDisk("disk.img", "RAW", FileAccess.ReadWrite, null, null) ?? throw new FileNotFoundException(); ``` ### Response #### Success Response (VirtualDisk) - **DiskTypeInfo** (DiskTypeInfo) - Information about the virtual disk format. - **Capacity** (long) - The total capacity of the disk in bytes. - **IsPartitioned** (bool) - Indicates if the disk is partitioned. #### Response Example ```json { "DiskTypeInfo": { "Name": "VHD", "Description": "Microsoft Virtual Hard Disk" }, "Capacity": 53687091200, "IsPartitioned": true } ``` ``` -------------------------------- ### Enumerate volumes with VolumeManager Source: https://context7.com/ltrdata/discutils/llms.txt Use VolumeManager to scan virtual disks and list their physical and logical partitions. The detected volumes can then be used with FileSystemManager to identify and open file systems. ```csharp using DiscUtils; using DiscUtils.Complete; using System.IO; SetupHelper.SetupComplete(); using var disk = VirtualDisk.OpenDisk(@"C:\Images\system.vhd", FileAccess.Read)!; var volMgr = new VolumeManager(disk); foreach (var vol in volMgr.GetPhysicalVolumes()) { Console.WriteLine($"Physical: {vol.Identity} Length={vol.Length / 1024 / 1024} MB " + $ ``` -------------------------------- ### Thread-Safe Virtual Disk Access with DiscUtils Source: https://context7.com/ltrdata/discutils/llms.txt Wraps a VirtualDisk in a synchronized object for safe concurrent access from multiple threads. This is useful when multiple threads need to read from the same disk image simultaneously. ```csharp using DiscUtils; using DiscUtils.Complete; using DiscUtils.Streams; using System.IO; using System.Threading.Tasks; SetupHelper.SetupComplete(); using var disk = VirtualDisk.OpenDisk(@"C:\Images\shared.vhd", FileAccess.Read)!; using var syncDisk = disk.AsSynchronized(Ownership.None); // Multiple threads can now safely read from syncDisk await Task.WhenAll( Task.Run(() => { var mbr = syncDisk.GetMasterBootRecord(); Console.WriteLine($"Thread 1 MBR sig: 0x{syncDisk.Signature:X8}"); }), Task.Run(() => { Console.WriteLine($"Thread 2 capacity: {syncDisk.Capacity}"); }) ); ``` -------------------------------- ### CDReader Source: https://context7.com/ltrdata/discutils/llms.txt Opens an existing ISO or optical disc image for read-only file system access. ```APIDOC ## CDReader — Read ISO 9660 / UDF disc images Opens an existing ISO or optical disc image for read-only file system access. ### Usage ```csharp using var stream = File.OpenRead(@"C:\ISOs\ubuntu.iso"); using var reader = new CDReader(stream, joliet: true, hideVersions: true); Console.WriteLine($"Active variant : {reader.ActiveVariant}"); Console.WriteLine($"Volume label : {reader.VolumeLabel}"); Console.WriteLine($"Boot emulation : {reader.BootEmulation}"); // List all files recursively foreach (var path in reader.GetFiles("", "*", SearchOption.AllDirectories)) { var info = reader.GetFileInfo(path); Console.WriteLine($"{path} ({info.Length} bytes)"); } // Extract a specific file using var src = reader.OpenFile(@"README.md", FileMode.Open, FileAccess.Read); using var dst = File.Create(@"C:\Extracted\README.md"); src.CopyTo(dst); ``` ``` -------------------------------- ### Read ISO 9660 Disc Image with CDReader Source: https://context7.com/ltrdata/discutils/llms.txt Opens an existing ISO or optical disc image for read-only file system access. Supports Joliet and UDF variants. Ensure the stream is properly disposed. ```csharp using DiscUtils.Iso9660; using System.IO; using var stream = File.OpenRead(@"C:\ISOs\ubuntu.iso"); using var reader = new CDReader(stream, joliet: true, hideVersions: true); Console.WriteLine($"Active variant : {reader.ActiveVariant}"); Console.WriteLine($"Volume label : {reader.VolumeLabel}"); Console.WriteLine($"Boot emulation : {reader.BootEmulation}"); // List all files recursively foreach (var path in reader.GetFiles("", "*", SearchOption.AllDirectories)) { var info = reader.GetFileInfo(path); Console.WriteLine($"{path} ({info.Length} bytes)"); } // Extract a specific file using var src = reader.OpenFile(@"README.md", FileMode.Open, FileAccess.Read); using var dst = File.Create(@"C:\Extracted\README.md"); src.CopyTo(dst); ``` -------------------------------- ### VolumeManager Source: https://context7.com/ltrdata/discutils/llms.txt Scans virtual disks to enumerate physical and logical volumes. It provides information about partitions and their types, which can then be used to detect file systems. ```APIDOC ## VolumeManager — Enumerate physical and logical volumes Scans one or more virtual disks and enumerates their partitions as `PhysicalVolumeInfo` and `LogicalVolumeInfo` objects, which can be passed to `FileSystemManager.DetectFileSystems`. ### Methods - `GetPhysicalVolumes()`: Returns an enumeration of `PhysicalVolumeInfo` objects. - `GetLogicalVolumes()`: Returns an enumeration of `LogicalVolumeInfo` objects. ### PhysicalVolumeInfo Properties - `Identity` (string): The identity of the physical volume. - `Length` (long): The length of the physical volume in bytes. - `BiosType` (byte): The BIOS partition type. ### LogicalVolumeInfo Properties - `Identity` (string): The identity of the logical volume. - `Length` (long): The length of the logical volume in bytes. ### Example ```csharp using DiscUtils; using DiscUtils.Complete; using System.IO; // Assuming 'disk' is an opened VirtualDisk instance var volMgr = new VolumeManager(disk); foreach (var vol in volMgr.GetLogicalVolumes()) { Console.WriteLine($"Logical: {vol.Identity}"); } ``` ``` -------------------------------- ### NtfsFileSystem.Format Source: https://context7.com/ltrdata/discutils/llms.txt Formats a stream or virtual disk partition with a new NTFS file system. This method allows specifying volume label, disk geometry, and sector information. ```APIDOC ## NtfsFileSystem.Format — Format a stream with NTFS Creates a new NTFS volume on any writable stream or virtual disk partition. ### Parameters - `stream` (Stream): The stream to format. - `label` (string, optional): The volume label. - `diskGeometry` (DiskGeometry, optional): The disk geometry. - `firstSector` (long, optional): The starting sector of the partition. - `sectorCount` (long, optional): The number of sectors in the partition. ### Returns - `NtfsFileSystem`: An instance of the newly formatted NTFS file system. ### Example ```csharp using DiscUtils; using DiscUtils.Ntfs; using System.IO; // Assuming 'partStream' is an initialized writable stream var ntfs = NtfsFileSystem.Format(partStream, label: "MyVolume"); ``` ```