예제 #1
0
        private IRawFileSystem GetSystem(string path)
        {
            IRawFileSystem system;
            var            driveLetter = path[0];

            if (!char.IsLetter(driveLetter))
            {
                throw new ArgumentException($"Path '{path}' did not have a drive letter!");
            }

            if (systems.TryGetValue(driveLetter, out system))
            {
                return(system);
            }

            try
            {
                var disk          = new RawDisk(driveLetter);
                var rawDiskStream = disk.CreateDiskStream();
                system = new NtfsFileSystem(rawDiskStream);
                systems.Add(driveLetter, system);
            }
            catch (Exception)
            {
                Console.WriteLine("Failed to create a filesystem for drive '{0}'", driveLetter);
                throw;
            }
            return(system);
        }
예제 #2
0
        public NtfsFileStream(NtfsFileSystem fileSystem, DirectoryEntry entry, AttributeType attrType, string attrName, FileAccess access)
        {
            _entry = entry;

            _file       = fileSystem.GetFile(entry.Reference);
            _baseStream = _file.OpenStream(attrType, attrName, access);
        }
예제 #3
0
        public void ShortNames()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            // Check we can find a short name in the same directory
            using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) {}
            ntfs.SetShortName("ALongFileName.txt", "ALONG~01.TXT");
            Assert.Equal("ALONG~01.TXT", ntfs.GetShortName("ALongFileName.txt"));
            Assert.True(ntfs.FileExists("ALONG~01.TXT"));

            // Check path handling
            ntfs.CreateDirectory("DIR");
            using (Stream s = ntfs.OpenFile(@"DIR\ALongFileName2.txt", FileMode.CreateNew)) { }
            ntfs.SetShortName(@"DIR\ALongFileName2.txt", "ALONG~02.TXT");
            Assert.Equal("ALONG~02.TXT", ntfs.GetShortName(@"DIR\ALongFileName2.txt"));
            Assert.True(ntfs.FileExists(@"DIR\ALONG~02.TXT"));

            // Check we can open a file by the short name
            using (Stream s = ntfs.OpenFile("ALONG~01.TXT", FileMode.Open)) { }

            // Delete the long name, and make sure the file is gone
            ntfs.DeleteFile("ALONG~01.TXT");
            Assert.False(ntfs.FileExists("ALONG~01.TXT"));

            // Delete the short name, and make sure the file is gone
            ntfs.DeleteFile(@"DIR\ALONG~02.TXT");
            Assert.False(ntfs.FileExists(@"DIR\ALongFileName2.txt"));
        }
예제 #4
0
        /// <summary>
        /// This method creates a .vhd hard drive formatted in NTFS.
        /// </summary>
        /// <param name="diskSize">The size of the disk in bytes.</param>
        /// <param name="location">Defines the physical location and file name. .vhd extension required.</param>
        /// <param name="label">The label to be given to the disk.</param>
        /// <param name="dynamic">Determines whether or not the disk will be of fixed size or dynamic size.</param>
        /// <returns>A bool determining if the method succeeded.</returns>
        public bool CreateNtfsDrive(long diskSize, string location, string label, bool dynamic)
        {
            try
            {
                using (Stream vhdStream = File.Create(@location))
                {
                    Disk disk = null;

                    if (dynamic)
                    {
                        disk = Disk.InitializeDynamic(vhdStream, Ownership.None, diskSize);
                    }
                    else
                    {
                        disk = Disk.InitializeFixed(vhdStream, Ownership.None, diskSize);
                    }

                    BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
                    NtfsFileSystem.Format(new VolumeManager(disk).GetLogicalVolumes()[0], label);

                    return(true);
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.StackTrace);
                return(false);
            }
        }
예제 #5
0
        public static DiscFileSystem FormatStream(string fileSystemName, Stream stream, long size, string label)
        {
            switch (fileSystemName)
            {
            case "NTFS":
            {
                var geometry = FindBasicGeometry(stream, size);

                Logger.Info("Formatting stream as NTFS");
                return(NtfsFileSystem.Format(stream, label, geometry, 0, geometry.TotalSectorsLong));
            }

            case "FAT":
            {
                var geometry = FindBasicGeometry(stream, size);

                Logger.Info("Formatting stream as FAT");
#pragma warning disable CS0618 // Typ oder Element ist veraltet
                return(FatFileSystem.FormatPartition(stream, label, geometry, 0, geometry.TotalSectors, 0));

#pragma warning restore CS0618 // Typ oder Element ist veraltet
            }

            default:
            {
                Logger.Error("Requested file system is not supported (Requested {0}, supported: NTFS, FAT)",
                             fileSystemName);
                Environment.Exit(1);
                break;
            }
            }

            return(null);
        }
예제 #6
0
        public void GetFileLength()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            ntfs.OpenFile(@"AFILE.TXT", FileMode.Create).Dispose();
            Assert.Equal(0, ntfs.GetFileLength("AFILE.TXT"));

            using (var stream = ntfs.OpenFile(@"AFILE.TXT", FileMode.Open))
            {
                stream.Write(new byte[14325], 0, 14325);
            }
            Assert.Equal(14325, ntfs.GetFileLength("AFILE.TXT"));

            using (var attrStream = ntfs.OpenFile(@"AFILE.TXT:altstream", FileMode.Create))
            {
                attrStream.Write(new byte[122], 0, 122);
            }
            Assert.Equal(122, ntfs.GetFileLength("AFILE.TXT:altstream"));


            // Test NTFS options for hardlink behaviour
            ntfs.CreateDirectory("Dir");
            ntfs.CreateHardLink("AFILE.TXT", @"Dir\OtherLink.txt");

            using (var stream = ntfs.OpenFile("AFILE.TXT", FileMode.Open, FileAccess.ReadWrite))
            {
                stream.SetLength(50);
            }
            Assert.Equal(50, ntfs.GetFileLength("AFILE.TXT"));
            Assert.Equal(14325, ntfs.GetFileLength(@"Dir\OtherLink.txt"));

            ntfs.NtfsOptions.FileLengthFromDirectoryEntries = false;

            Assert.Equal(50, ntfs.GetFileLength(@"Dir\OtherLink.txt"));
        }
예제 #7
0
        void InitializeVhdManually(DiscUtils.Vhd.Disk vhdDisk)
        {
            BiosPartitionTable.Initialize(vhdDisk, WellKnownPartitionType.WindowsNtfs);
            // GuidPartitionTable.Initialize(vhdDisk,  WellKnownPartitionType.WindowsNtfs);

            var volMgr        = new VolumeManager(vhdDisk);
            var logicalVolume = volMgr.GetLogicalVolumes()[0];

            var label = $"XVDTool conversion";

            using (var destNtfs = NtfsFileSystem.Format(logicalVolume, label, new NtfsFormatOptions()))
            {
                destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;

                // NOTE: For VHD creation we just assume a single partition
                foreach (var file in IterateFilesystem(partitionNumber: 0))
                {
                    var fh = file.OpenRead();

                    if (!destNtfs.Exists(file.DirectoryName))
                    {
                        destNtfs.CreateDirectory(file.DirectoryName);
                    }

                    using (Stream dest = destNtfs.OpenFile(file.FullName, FileMode.Create,
                                                           FileAccess.ReadWrite))
                    {
                        fh.CopyTo(dest);
                        dest.Flush();
                    }

                    fh.Close();
                }
            }
        }
예제 #8
0
        public static DiscFileSystem FormatFileSystemWithTemplate(Stream template, Stream output,
                                                                  long firstSector, long sectorCount, long availableSpace)
        {
            if (NtfsFileSystem.Detect(template))
            {
                var templateFS = new NtfsFileSystem(template);
                var newSize    = Math.Min(templateFS.Size, availableSpace);

                Logger.Verbose("Formatting stream as <NTFS> file system ({0}B, 0x{1}-0x{2})",
                               newSize, firstSector.ToString("X2"), sectorCount.ToString("X2"));

                return(NtfsFileSystem.Format(output, templateFS.VolumeLabel,
                                             Geometry.FromCapacity(newSize), firstSector, sectorCount,
                                             templateFS.ReadBootCode()));
            }

            /* else if (FatFileSystem.Detect(template))
             * {
             *  var templateFS = new FatFileSystem(template);
             *  var newSize = Math.Min(templateFS.Size, availableSpace);
             *
             *  Logger.Verbose("Formatting streams as <FAT> ({0}B, 0x{1}-0x{2})",
             *      newSize, firstSector.ToString("X2"), sectorCount.ToString("X2"));
             *
             *  return FatFileSystem.FormatPartition(output, templateFS.VolumeLabel,
             *      Geometry.FromCapacity(newSize), (int)firstSector, (int)sectorCount, 13);
             * } */

            return(null);
        }
        protected override void ProcessRecord()
        {
            PSObject   volInfoObj = null;
            VolumeInfo volInfo    = null;

            if (InputObject != null)
            {
                volInfoObj = InputObject;
                volInfo    = volInfoObj.BaseObject as VolumeInfo;
            }
            if (volInfo == null && string.IsNullOrEmpty(LiteralPath))
            {
                WriteError(new ErrorRecord(
                               new ArgumentException("No volume specified"),
                               "NoVolumeSpecified",
                               ErrorCategory.InvalidArgument,
                               null));
                return;
            }

            if (Filesystem != FileSystemType.Ntfs)
            {
                WriteError(new ErrorRecord(
                               new ArgumentException("Unknown filesystem type"),
                               "BadFilesystem",
                               ErrorCategory.InvalidArgument,
                               null));
                return;
            }

            if (volInfo == null)
            {
                volInfoObj = SessionState.InvokeProvider.Item.Get(LiteralPath)[0];
                volInfo    = volInfoObj.BaseObject as VolumeInfo;
            }

            if (volInfo == null)
            {
                WriteError(new ErrorRecord(
                               new ArgumentException("Path specified is not a disk volume"),
                               "BadVolumeSpecified",
                               ErrorCategory.InvalidArgument,
                               null));
                return;
            }

            var driveProp = volInfoObj.Properties["PSDrive"];

            if (driveProp != null)
            {
                var drive = driveProp.Value as VirtualDiskPSDriveInfo;
                if (drive != null)
                {
                    drive.UncacheFileSystem(volInfo.Identity);
                }
            }

            NtfsFileSystem.Format(volInfo, Label);
        }
예제 #10
0
        public void OpenRawStream()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

#pragma warning disable 618
            Assert.Null(ntfs.OpenRawStream(@"$Extend\$ObjId", AttributeType.Data, null, FileAccess.Read));
#pragma warning restore 618
        }
예제 #11
0
        public static IFileSystem GetFileSystem(char driveLetter, FileAccess fileAccess)
        {
            var disk          = new RawDisk(driveLetter, fileAccess);
            var rawDiskStream = disk.CreateDiskStream();
            var system        = new NtfsFileSystem(rawDiskStream);

            return(system);
        }
예제 #12
0
        public void Fragmented()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            ntfs.CreateDirectory(@"DIR");

            byte[] buffer = new byte[4096];

            for (int i = 0; i < 2500; ++i)
            {
                using (var stream = ntfs.OpenFile(@"DIR\file" + i + ".bin", FileMode.Create, FileAccess.ReadWrite))
                {
                    stream.Write(buffer, 0, buffer.Length);
                }

                using (var stream = ntfs.OpenFile(@"DIR\" + i + ".bin", FileMode.Create, FileAccess.ReadWrite))
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            for (int i = 0; i < 2500; ++i)
            {
                ntfs.DeleteFile(@"DIR\file" + i + ".bin");
            }

            // Create fragmented file (lots of small writes)
            using (var stream = ntfs.OpenFile(@"DIR\fragmented.bin", FileMode.Create, FileAccess.ReadWrite))
            {
                for (int i = 0; i < 2500; ++i)
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }

            // Try a large write
            byte[] largeWriteBuffer = new byte[200 * 1024];
            for (int i = 0; i < largeWriteBuffer.Length / 4096; ++i)
            {
                largeWriteBuffer[i * 4096] = (byte)i;
            }
            using (var stream = ntfs.OpenFile(@"DIR\fragmented.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                stream.Position = stream.Length - largeWriteBuffer.Length;
                stream.Write(largeWriteBuffer, 0, largeWriteBuffer.Length);
            }

            // And a large read
            byte[] largeReadBuffer = new byte[largeWriteBuffer.Length];
            using (var stream = ntfs.OpenFile(@"DIR\fragmented.bin", FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                stream.Position = stream.Length - largeReadBuffer.Length;
                stream.Read(largeReadBuffer, 0, largeReadBuffer.Length);
            }

            Assert.Equal(largeWriteBuffer, largeReadBuffer);
        }
예제 #13
0
        public void Sparse()
        {
            int fileSize = 1 * 1024 * 1024;

            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            byte[] data = new byte[fileSize];
            for (int i = 0; i < fileSize; i++)
            {
                data[i] = (byte)i;
            }

            using (SparseStream s = ntfs.OpenFile("file.bin", FileMode.CreateNew))
            {
                s.Write(data, 0, fileSize);

                ntfs.SetAttributes("file.bin", ntfs.GetAttributes("file.bin") | FileAttributes.SparseFile);

                s.Position = 64 * 1024;
                s.Clear(128 * 1024);
                s.Position = fileSize - 64 * 1024;
                s.Clear(128 * 1024);
            }

            using (SparseStream s = ntfs.OpenFile("file.bin", FileMode.Open))
            {
                Assert.Equal(fileSize + 64 * 1024, s.Length);

                List <StreamExtent> extents = new List <StreamExtent>(s.Extents);

                Assert.Equal(2, extents.Count);
                Assert.Equal(0, extents[0].Start);
                Assert.Equal(64 * 1024, extents[0].Length);
                Assert.Equal((64 + 128) * 1024, extents[1].Start);
                Assert.Equal(fileSize - (64 * 1024) - ((64 + 128) * 1024), extents[1].Length);


                s.Position = 72 * 1024;
                s.WriteByte(99);

                byte[] readBuffer = new byte[fileSize];
                s.Position = 0;
                s.Read(readBuffer, 0, fileSize);

                for (int i = 64 * 1024; i < (128 + 64) * 1024; ++i)
                {
                    data[i] = 0;
                }
                for (int i = fileSize - (64 * 1024); i < fileSize; ++i)
                {
                    data[i] = 0;
                }
                data[72 * 1024] = 99;

                Assert.Equal(data, readBuffer);
            }
        }
예제 #14
0
        public override DiscUtils.FileSystemInfo[] Detect(Stream stream, VolumeInfo volume)
        {
            if (NtfsFileSystem.Detect(stream))
            {
                return(new DiscUtils.FileSystemInfo[] { new VfsFileSystemInfo("NTFS", "Microsoft NTFS", Open) });
            }

            return(new DiscUtils.FileSystemInfo[0]);
        }
예제 #15
0
        public void Format_LargeDisk()
        {
            long size = 1024L * 1024 * 1024L * 1024; // 1 TB
            SparseMemoryStream partStream = new SparseMemoryStream();

            NtfsFileSystem.Format(partStream, "New Partition", Geometry.FromCapacity(size), 0, size / 512);

            NtfsFileSystem ntfs = new NtfsFileSystem(partStream);

            ntfs.Dump(TextWriter.Null, "");
        }
예제 #16
0
        public void GetAlternateDataStreams()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            ntfs.OpenFile("AFILE.TXT", FileMode.Create).Dispose();
            Assert.Equal(0, ntfs.GetAlternateDataStreams("AFILE.TXT").Length);

            ntfs.OpenFile("AFILE.TXT:ALTSTREAM", FileMode.Create).Dispose();
            Assert.Equal(1, ntfs.GetAlternateDataStreams("AFILE.TXT").Length);
            Assert.Equal("ALTSTREAM", ntfs.GetAlternateDataStreams("AFILE.TXT")[0]);
        }
예제 #17
0
        public void Format_SmallDisk()
        {
            long size = 8 * 1024 * 1024;
            SparseMemoryStream partStream = new SparseMemoryStream();

            //VirtualDisk disk = Vhd.Disk.InitializeDynamic(partStream, Ownership.Dispose, size);
            NtfsFileSystem.Format(partStream, "New Partition", Geometry.FromCapacity(size), 0, size / 512);

            NtfsFileSystem ntfs = new NtfsFileSystem(partStream);

            ntfs.Dump(TextWriter.Null, "");
        }
예제 #18
0
        private static void CreateVirtualDisk(string filePath, int size)
        {
            using (FileStream fsStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                using (VirtualDisk disk = DiscUtils.Vhd.Disk.InitializeDynamic(fsStream, DiscUtils.Streams.Ownership.Dispose, size * 1024 * 1024))
                {
                    GuidPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);

                    PhysicalVolumeInfo volume = VolumeManager.GetPhysicalVolumes(disk)[0];

                    NtfsFileSystem.Format(volume, "CryptoBox");
                }
        }
예제 #19
0
        public void ReparsePoints_NonEmpty()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            ntfs.CreateDirectory("dir");
            ntfs.SetReparsePoint("dir", new ReparsePoint(123, new byte[] { 4, 5, 6 }));

            ReparsePoint rp = ntfs.GetReparsePoint("dir");

            Assert.Equal(123, rp.Tag);
            Assert.NotNull(rp.Content);
            Assert.Equal(3, rp.Content.Length);
        }
예제 #20
0
        public void DeleteShortNameDir()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            ntfs.CreateDirectory(@"\TestLongName1\TestLongName2");
            ntfs.SetShortName(@"\TestLongName1\TestLongName2", "TESTLO~1");

            Assert.True(ntfs.DirectoryExists(@"\TestLongName1\TESTLO~1"));
            Assert.True(ntfs.DirectoryExists(@"\TestLongName1\TestLongName2"));

            ntfs.DeleteDirectory(@"\TestLongName1", true);

            Assert.False(ntfs.DirectoryExists(@"\TestLongName1"));
        }
예제 #21
0
 private void CreateDisk(string targetFilePath, long size, string diskLabel)
 {
     // Create the disk
     using (var vhdStream = File.Create(targetFilePath))
     {
         var disk = Disk.InitializeDynamic(vhdStream, Ownership.None, size);
         BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
         using (var fs = NtfsFileSystem.Format(new VolumeManager(disk).GetLogicalVolumes()[0], diskLabel))
         {
             //fs.CreateDirectory(@"TestDir\CHILD");
             // do other things with the file system...
         }
     }
 }
예제 #22
0
        /// <summary>
        /// Creates a temporary vhd of the given size in GB.
        /// The created VHD is dynamically allocated and is of type VHD (legacy)
        /// </summary>
        /// <param name="sizeInGB">The size of the VHD in GB</param>
        /// <returns>The path to the created vhd</returns>
        internal static string CreateVirtualDisk(long sizeInGB = 10)
        {
            long   diskSize = sizeInGB * 1024 * 1024 * 1024;
            string tempVhd  = Path.GetTempFileName();

            using Stream vhdStream = File.Create(tempVhd);
            using Disk disk        = Disk.InitializeDynamic(vhdStream, DiscUtils.Streams.Ownership.Dispose, diskSize);

            BiosPartitionTable table         = BiosPartitionTable.Initialize(disk, WellKnownPartitionType.WindowsNtfs);
            PartitionInfo      ntfsPartition = table.Partitions[0];

            NtfsFileSystem.Format(ntfsPartition.Open(), "Windows UUP Medium", Geometry.FromCapacity(diskSize), ntfsPartition.FirstSector, ntfsPartition.SectorCount);

            return(tempVhd);
        }
예제 #23
0
        public static DiscFileSystem GetFileSystem(Stream stream)
        {
            if (NtfsFileSystem.Detect(stream))
            {
                Logger.Verbose("Loading stream as <NTFS> file system");
                return(new NtfsFileSystem(stream));
            }

            /* if (FatFileSystem.Detect(stream))
             * {
             *  Logger.Verbose("Loading stream as <FAT> file system");
             *  return new FatFileSystem(stream);
             * } */

            return(null);
        }
예제 #24
0
        public void HasHardLink()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { }
            Assert.False(ntfs.HasHardLinks("ALongFileName.txt"));

            ntfs.CreateHardLink("ALongFileName.txt", "AHardLink.TXT");
            Assert.True(ntfs.HasHardLinks("ALongFileName.txt"));

            using (Stream s = ntfs.OpenFile("ALongFileName2.txt", FileMode.CreateNew)) { }

            // If we enumerate short names, then the initial long name results in two 'hardlinks'
            ntfs.NtfsOptions.HideDosFileNames = false;
            Assert.True(ntfs.HasHardLinks("ALongFileName2.txt"));
        }
예제 #25
0
        public void ExtentInfo()
        {
            using (SparseMemoryStream ms = new SparseMemoryStream())
            {
                Geometry       diskGeometry = Geometry.FromCapacity(30 * 1024 * 1024);
                NtfsFileSystem ntfs         = NtfsFileSystem.Format(ms, "", diskGeometry, 0, diskGeometry.TotalSectorsLong);

                // Check non-resident attribute
                using (Stream s = ntfs.OpenFile(@"file", FileMode.Create, FileAccess.ReadWrite))
                {
                    byte[] data = new byte[(int)ntfs.ClusterSize];
                    data[0] = 0xAE;
                    data[1] = 0x3F;
                    data[2] = 0x8D;
                    s.Write(data, 0, (int)ntfs.ClusterSize);
                }

                var extents = ntfs.PathToExtents("file");
                Assert.Equal(1, extents.Length);
                Assert.Equal(ntfs.ClusterSize, extents[0].Length);

                ms.Position = extents[0].Start;
                Assert.Equal(0xAE, ms.ReadByte());
                Assert.Equal(0x3F, ms.ReadByte());
                Assert.Equal(0x8D, ms.ReadByte());


                // Check resident attribute
                using (Stream s = ntfs.OpenFile(@"file2", FileMode.Create, FileAccess.ReadWrite))
                {
                    s.WriteByte(0xBA);
                    s.WriteByte(0x82);
                    s.WriteByte(0x2C);
                }
                extents = ntfs.PathToExtents("file2");
                Assert.Equal(1, extents.Length);
                Assert.Equal(3, extents[0].Length);

                byte[] read = new byte[100];
                ms.Position = extents[0].Start;
                ms.Read(read, 0, 100);

                Assert.Equal(0xBA, read[0]);
                Assert.Equal(0x82, read[1]);
                Assert.Equal(0x2C, read[2]);
            }
        }
예제 #26
0
        public static bool IsStreamSupportedFileSystem(Stream stream)
        {
            if (NtfsFileSystem.Detect(stream))
            {
                Logger.Verbose("Detected stream as <NTFS> file system");
                return(true);
            }

            /* if (FatFileSystem.Detect(stream))
             * {
             *  Logger.Verbose("Detected stream as <FAT> file-system");
             *  return true;
             * } */

            // only NTFS can be detected and formatted right now
            return(false);
        }
예제 #27
0
        public void HardLinkCount()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { }
            Assert.Equal(1, ntfs.GetHardLinkCount("ALongFileName.txt"));

            ntfs.CreateHardLink("ALongFileName.txt", "AHardLink.TXT");
            Assert.Equal(2, ntfs.GetHardLinkCount("ALongFileName.txt"));

            ntfs.CreateDirectory("DIR");
            ntfs.CreateHardLink(@"ALongFileName.txt", @"DIR\SHORTLNK.TXT");
            Assert.Equal(3, ntfs.GetHardLinkCount("ALongFileName.txt"));

            // If we enumerate short names, then the initial long name results in two 'hardlinks'
            ntfs.NtfsOptions.HideDosFileNames = false;
            Assert.Equal(4, ntfs.GetHardLinkCount("ALongFileName.txt"));
        }
예제 #28
0
        public void AclInheritance()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            RawSecurityDescriptor sd = new RawSecurityDescriptor("O:BAG:BAD:(A;OICINP;GA;;;BA)");

            ntfs.CreateDirectory("dir");
            ntfs.SetSecurity("dir", sd);

            ntfs.CreateDirectory(@"dir\subdir");
            RawSecurityDescriptor inheritedSd = ntfs.GetSecurity(@"dir\subdir");

            Assert.NotNull(inheritedSd);
            Assert.Equal("O:BAG:BAD:(A;ID;GA;;;BA)", inheritedSd.GetSddlForm(AccessControlSections.All));

            using (ntfs.OpenFile(@"dir\subdir\file", FileMode.Create, FileAccess.ReadWrite)) { }
            inheritedSd = ntfs.GetSecurity(@"dir\subdir\file");
            Assert.NotNull(inheritedSd);
            Assert.Equal("O:BAG:BAD:", inheritedSd.GetSddlForm(AccessControlSections.All));
        }
예제 #29
0
        public void MoveLongName()
        {
            NtfsFileSystem ntfs = FileSystemSource.NtfsFileSystem();

            using (Stream s = ntfs.OpenFile("ALongFileName.txt", FileMode.CreateNew)) { }

            Assert.True(ntfs.FileExists("ALONGF~1.TXT"));

            ntfs.MoveFile("ALongFileName.txt", "ADifferentLongFileName.txt");

            Assert.False(ntfs.FileExists("ALONGF~1.TXT"));
            Assert.True(ntfs.FileExists("ADIFFE~1.TXT"));

            ntfs.CreateDirectory("ALongDirectoryName");
            Assert.True(ntfs.DirectoryExists("ALONGD~1"));

            ntfs.MoveDirectory("ALongDirectoryName", "ADifferentLongDirectoryName");
            Assert.False(ntfs.DirectoryExists("ALONGD~1"));
            Assert.True(ntfs.DirectoryExists("ADIFFE~1"));
        }
예제 #30
0
        /// <summary>
        /// Creates local VHD files, using the parameters specified.
        /// </summary>
        /// <param name="isDynamic">True to create a dynamic VHD, False to create a fixed VHD.</param>
        /// <param name="diskSizeInGb">Size of the VHD in gigabytes.</param>
        /// <param name="filePath">Path of the VHD file.</param>
        /// <param name="diskName">Name of the volume of the VHD.</param>
        public static void CreateVhdDisk(bool isDynamic, int diskSizeInGb, string filePath, string diskName)
        {
            var diskSize = (long)ByteSize.FromGigaBytes(diskSizeInGb).Bytes;

            using (var fs = new FileStream(filePath, FileMode.OpenOrCreate))
            {
                using (VirtualDisk destDisk = isDynamic ? Disk.InitializeDynamic(fs, Ownership.None, diskSize)
                                                        : Disk.InitializeFixed(fs, Ownership.None, diskSize))
                {
                    BiosPartitionTable.Initialize(destDisk, WellKnownPartitionType.WindowsNtfs);
                    var volumeManager = new VolumeManager(destDisk);

                    using (var destNtfs = NtfsFileSystem.Format(volumeManager.GetLogicalVolumes().FirstOrDefault(), diskName, new NtfsFormatOptions()))
                    {
                        destNtfs.NtfsOptions.ShortNameCreation = ShortFileNameOption.Disabled;
                    }
                }
                fs.Flush(); // commit everything to the stream before closing
            }
        }