Guest User

Untitled

a guest
Sep 17th, 2015
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.35 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Text;
  5. using Microsoft.Win32.SafeHandles;
  6.  
  7. namespace ConsoleApplication1
  8. {
  9.     internal class Program
  10.     {
  11.         private static void Main(string[] args)
  12.         {
  13.             long position = 0;
  14.             const int bWidth = 16;
  15.             SafeFileHandle handle = null;
  16.  
  17.             try
  18.             {
  19.                 handle = CreateFile("\\\\.\\PhysicalDrive0", FileAccess.Read, FileShare.Write | FileShare.Read | FileShare.Delete, IntPtr.Zero, FileMode.Open, FileAttributes.System, IntPtr.Zero);
  20.  
  21.                 if (handle.IsInvalid)
  22.                 {
  23.                     Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
  24.                 }
  25.  
  26.                 using (var fs = new FileStream(handle, FileAccess.Read))
  27.                 {
  28.                     using (var br = new BinaryReader(fs, Encoding.UTF8))
  29.                     {
  30.                         while (fs.Position < 512)
  31.                         {
  32.                             Console.Write($"{position:X8}    ");
  33.  
  34.                             var bytes = br.ReadBytes(bWidth);
  35.  
  36.                             foreach (var b in bytes)
  37.                             {
  38.                                 Console.Write($"{b:X2} ");
  39.                             }
  40.  
  41.                             Console.WriteLine($"    {Encoding.UTF8.GetString(bytes)}");
  42.                             position = fs.Position;
  43.                         }
  44.                     }
  45.                 }
  46.             }
  47.             catch (Exception ex)
  48.             {
  49.                 Console.WriteLine(ex);
  50.             }
  51.             finally
  52.             {
  53.                 handle?.Close();
  54.             }
  55.  
  56.             Console.WriteLine("Press any key to close.");
  57.             Console.ReadKey();
  58.         }
  59.  
  60.  
  61.         [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  62.         static extern SafeFileHandle CreateFile(
  63.             string lpFileName,
  64.             [MarshalAs(UnmanagedType.U4)] FileAccess dwDesiredAccess,
  65.             [MarshalAs(UnmanagedType.U4)] FileShare dwShareMode,
  66.             IntPtr lpSecurityAttributes,
  67.             [MarshalAs(UnmanagedType.U4)] FileMode dwCreationDisposition,
  68.             [MarshalAs(UnmanagedType.U4)] FileAttributes dwFlagsAndAttributes,
  69.             IntPtr hTemplateFile);
  70.     }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment