Beispiel #1
0
        public override void Execute()
        {
            IEnumerable<char> volumeDrives = Utils.GetAllAvailableVolumes();

            foreach (char device in volumeDrives)
            {
                Console.WriteLine("Trying volume, " + device + ": .. ");

                try
                {
                    using (RawDisk disk = new RawDisk(device))
                    {
                        ExampleUtilities.PresentResult(disk);
                    }
                }
                catch (Win32Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: " + new Win32Exception(exception.NativeErrorCode).Message);
                    Console.ForegroundColor = ExampleUtilities.DefaultColor;
                }

                Console.WriteLine();
            }
        }
        public override void Execute()
        {
            IEnumerable<int> physicalDrives = Utils.GetAllAvailableDrives(DiskNumberType.PhysicalDisk);

            foreach (int device in physicalDrives)
            {
                Console.WriteLine("Trying PhysicalDrive" + device + ": .. ");

                try
                {
                    using (RawDisk disk = new RawDisk(DiskNumberType.PhysicalDisk, device))
                    {
                        ExampleUtilities.PresentResult(disk);
                    }
                }
                catch (Win32Exception exception)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: " + new Win32Exception(exception.NativeErrorCode).Message);
                    Console.ForegroundColor = ExampleUtilities.DefaultColor;
                }

                Console.WriteLine();
            }
        }
        public static void PresentResult(RawDisk disk)
        {
            byte[] data = disk.ReadClusters(0, (int)Math.Min(disk.ClusterCount, ClustersToRead));

            string fatType = Encoding.ASCII.GetString(data, 82, 8);     // Extended FAT parameters have a display name here.
            bool isFat = fatType.StartsWith("FAT");
            bool isNTFS = Encoding.ASCII.GetString(data, 3, 4) == "NTFS";

            // Optimization, if it's a known FS, we know it's not all zeroes.
            bool allZero = (!isNTFS || !isFat) && data.All(s => s == 0);

            Console.WriteLine("Size in bytes : {0:N0}", disk.SizeBytes);
            Console.WriteLine("Sectors       : {0:N0}", disk.ClusterCount);
            Console.WriteLine("SectorSize    : {0:N0}", disk.SectorSize);
            Console.WriteLine("ClusterCount  : {0:N0}", disk.ClusterCount);
            Console.WriteLine("ClusterSize   : {0:N0}", disk.ClusterSize);

            if (!isFat && !isNTFS)
                Console.ForegroundColor = ConsoleColor.Red;

            if (isNTFS)
                Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("Is NTFS       : {0}", isNTFS);
            Console.ForegroundColor = DefaultColor;

            if (!isFat && !isNTFS)
                Console.ForegroundColor = ConsoleColor.Red;

            if (isFat)
                Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("Is FAT        : {0}", isFat ? fatType : "False");
            Console.ForegroundColor = DefaultColor;

            if (!allZero)
                Console.ForegroundColor = ConsoleColor.Green;
            else
                Console.ForegroundColor = ConsoleColor.Red;

            Console.WriteLine("All bytes zero: {0}", allZero);
            Console.ForegroundColor = DefaultColor;
        }
        public static void CopyFile(string sourceFile, string dstFile)
        {
            // FileAttributes 0x20000000L = FILE_FLAG_NO_BUFFERING
            SafeFileHandle fileHandle = Win32Helper.CreateFile(sourceFile, (FileAccess)Program.FILE_READ_ATTRIBUTES, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal | (FileAttributes)0x20000000L, IntPtr.Zero);

            if (fileHandle.IsInvalid)
                throw new ArgumentException("Invalid file: " + sourceFile);

            //var driveWrapper = new DeviceIOControlWrapper(driveHandle);
            FilesystemDeviceWrapper fileWrapper = new FilesystemDeviceWrapper(fileHandle);

            FileExtentInfo[] extents = fileWrapper.FileSystemGetRetrievalPointers();
            decimal totalSize = extents.Sum(s => (decimal)s.Size);
            decimal copiedBytes = 0;

            using (RawDisk disk = new RawDisk(char.ToUpper(sourceFile[0])))
            {
                // Write to the source file
                using (FileStream fs = new FileStream(dstFile, FileMode.Create))
                {
                    // Copy all extents
                    foreach (FileExtentInfo fileExtentInfo in extents)
                    {
                        // Copy chunks of data
                        for (ulong offset = 0; offset < fileExtentInfo.Size; offset += 10000)
                        {
                            int currentSizeBytes = (int)Math.Min(10000, fileExtentInfo.Size - offset);
                            byte[] data = disk.ReadClusters((long)(fileExtentInfo.Lcn + offset), currentSizeBytes);
                            fs.Write(data, 0, data.Length);

                            copiedBytes += currentSizeBytes;
                        }
                    }
                }
            }

            Debug.Assert(copiedBytes == totalSize);
        }
        public override void Execute()
        {
            IEnumerable<char> volumeDrives = Utils.GetAllAvailableVolumes();
            IEnumerable<int> harddiskVolumes = Utils.GetAllAvailableDrives(DiskNumberType.Volume);

            Console.WriteLine("You need to enter a volume on which to write and read. Note that this volume will be useless afterwards - do not chose anything by test volumes!");
            Console.WriteLine("Select volume:");
            List<int> options = new List<int>();

            foreach (int harddiskVolume in harddiskVolumes)
            {
                try
                {
                    using (RawDisk disk = new RawDisk(DiskNumberType.Volume, harddiskVolume))
                    {
                        char[] driveLetters = DiskHelper.GetDriveLetters(disk.DosDeviceName.Remove(0, @"\\.\GLOBALROOT".Length)).Where(volumeDrives.Contains).ToArray();

                        Console.WriteLine("  {0:N0}: {1:N0} Bytes, Drive Letters: {2}", harddiskVolume, disk.SizeBytes, string.Join(", ", driveLetters));
                        options.Add(harddiskVolume);
                    }
                }
                catch (Exception)
                {
                    // Don't write it
                }
            }

            string vol;
            int selectedVol;
            do
            {
                Console.WriteLine("Enter #:");
                vol = Console.ReadLine();
            } while (!(int.TryParse(vol, out selectedVol) && options.Contains(selectedVol)));

            Console.WriteLine("Selected " + selectedVol + ".");

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Are you sure? Type YES.");
            Console.ForegroundColor = ExampleUtilities.DefaultColor;

            bool allSuccess = false;

            string confirm = Console.ReadLine();
            if (confirm == "YES")
            {
                Console.WriteLine("Confirmed - starting");

                using (RawDisk disk = new RawDisk(DiskNumberType.Volume, selectedVol, FileAccess.ReadWrite))
                {
                    long chunks = disk.ClusterCount / ExampleUtilities.ClustersToRead;

                    Console.WriteLine("Disk {0} is {1:N0} Bytes large.", disk.DosDeviceName, disk.SizeBytes);
                    Console.WriteLine("Beginning random write in {0:N0} cluster chunks of {1:N0} Bytes each", ExampleUtilities.ClustersToRead, disk.ClusterSize);
                    Console.WriteLine(" # of chunks: {0:N0}", chunks);

                    byte[] chunkData = new byte[disk.ClusterSize * ExampleUtilities.ClustersToRead];
                    byte[] readData = new byte[disk.ClusterSize * ExampleUtilities.ClustersToRead];
                    Random rand = new Random();

                    StringBuilder blankLineBuilder = new StringBuilder(Console.BufferWidth);
                    for (int i = 0; i < Console.BufferWidth; i++)
                        blankLineBuilder.Append(' ');
                    string blankLine = blankLineBuilder.ToString();

                    allSuccess = true;

                    for (int chunk = 0; chunk < chunks; chunk++)
                    {
                        rand.NextBytes(chunkData);

                        Console.Write("Chunk #{0}: ", chunk);

                        try
                        {
                            // Write
                            Console.Write("Writing ... ");

                            disk.WriteClusters(chunkData, chunk * ExampleUtilities.ClustersToRead);

                            // Read
                            Console.Write("Reading ... ");

                            disk.ReadClusters(readData, 0, chunk * ExampleUtilities.ClustersToRead, (int)ExampleUtilities.ClustersToRead);

                            // Check
                            if (chunkData.SequenceEqual(readData))
                            {
                                Console.ForegroundColor = ConsoleColor.Green;
                                Console.WriteLine("Confirmed!");
                                Console.ForegroundColor = ExampleUtilities.DefaultColor;
                            }
                            else
                            {
                                allSuccess = false;

                                Console.ForegroundColor = ConsoleColor.Red;
                                Console.WriteLine("Failed!");
                                Console.ForegroundColor = ExampleUtilities.DefaultColor;

                                Console.WriteLine("Presse enter to proceed.");
                                Console.ReadLine();
                            }
                        }
                        catch (Exception ex)
                        {
                            allSuccess = false;

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Error: " + ex.Message);
                            Console.ForegroundColor = ExampleUtilities.DefaultColor;

                            Console.WriteLine("Presse enter to proceed.");
                            Console.ReadLine();

                            Console.CursorTop--;
                        }

                        Console.CursorTop--;
                        Console.CursorLeft = 0;
                        Console.Write(blankLine);
                        Console.CursorTop--;
                        Console.CursorLeft = 0;
                    }
                }
            }
            else
            {
                Console.WriteLine("Aborted");
            }

            if (allSuccess)
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("All chunks were able to write and read successfully.");
                Console.ForegroundColor = ExampleUtilities.DefaultColor;
            }
            else
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Some chunks were unable to be read correctly.");
                Console.ForegroundColor = ExampleUtilities.DefaultColor;
            }
        }
        public override void Execute()
        {
            // 512 MB
            const long lengthTodo = 512L * 1024 * 1024;

            IEnumerable<char> volumeDrives = Utils.GetAllAvailableVolumes();

            foreach (char drive in volumeDrives)
            {
                Console.WriteLine("Hashing " + drive + ":");

                try
                {
                    using (RawDisk disk = new RawDisk(drive))
                    {
                        long diskReadLength = Math.Min(disk.SizeBytes, lengthTodo);
                        long totalRead = 0;

                        // Read in ~16M chunks
                        int increment = (int)(((16f * 1024f * 1024f) / disk.SectorSize) * disk.SectorSize);

                        Console.WriteLine("Reading {0:N0} B in {1:N0} B chunks. Chunks: {2:N0}", diskReadLength, increment, diskReadLength / increment);

                        byte[] input = new byte[increment];
                        byte[] output = new byte[increment];

                        MD5 md5 = MD5.Create();

                        Stopwatch sw = new Stopwatch();

                        using (RawDiskStream diskFs = disk.CreateDiskStream())
                        {
                            sw.Start();
                            while (true)
                            {
                                int read = (int)Math.Min(increment, diskReadLength - diskFs.Position);
                                int actualRead = diskFs.Read(input, 0, read);

                                if (actualRead == 0)
                                {
                                    Console.CursorTop++;
                                    if (totalRead == diskReadLength)
                                    {
                                        Console.ForegroundColor = ConsoleColor.Green;
                                        Console.WriteLine("Done! Read {0:N0} in total", totalRead);
                                    }
                                    else
                                    {
                                        Console.ForegroundColor = ConsoleColor.Red;
                                        Console.WriteLine("Done! Read {0:N0} in total (not expected)", totalRead);
                                    }
                                    Console.ForegroundColor = ExampleUtilities.DefaultColor;

                                    break;
                                }

                                md5.TransformBlock(input, 0, actualRead, output, 0);

                                totalRead += actualRead;

                                Console.WriteLine("Position: {0:N0} B, Progress: {1:#0.000%}, AvgSpeed: {2:N2} MB/s", diskFs.Position, diskFs.Position * 1f / diskReadLength, (diskFs.Position / 1048576f) / sw.Elapsed.TotalSeconds);
                                Console.CursorTop--;
                            }
                            sw.Stop();
                        }

                        md5.TransformFinalBlock(new byte[0], 0, 0);

                        Console.Write("Computed MD5: ");
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine(BitConverter.ToString(md5.Hash).Replace("-", ""));
                        Console.ForegroundColor = ExampleUtilities.DefaultColor;
                    }
                }
                catch (Exception ex)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Error: " + ex.Message);
                    Console.ForegroundColor = ExampleUtilities.DefaultColor;
                }

                Console.WriteLine();
            }
        }