home *** CD-ROM | disk | FTP | other *** search
/ Programming in Microsoft Windows with C# / Programacion en Microsoft Windows con C#.iso / Original Code / Files and Streams / HexDump / HexDump.cs next >
Encoding:
Text File  |  2001-01-15  |  2.1 KB  |  72 lines

  1. //--------------------------------------
  2. // HexDump.cs ⌐ 2001 by Charles Petzold
  3. //--------------------------------------
  4. using System;
  5. using System.IO;
  6.  
  7. class HexDump
  8. {
  9.      public static int Main(string[] astrArgs)
  10.      {
  11.           if (astrArgs.Length == 0)
  12.           {
  13.                Console.WriteLine("Syntax: HexDump file1 file2 ...");
  14.                return 1;
  15.           }
  16.           foreach (string strFileName in astrArgs)
  17.                DumpFile(strFileName);
  18.  
  19.           return 0;
  20.      }
  21.      protected static void DumpFile(string strFileName)
  22.      {
  23.           FileStream fs;
  24.  
  25.           try
  26.           {
  27.                fs = new FileStream(strFileName, FileMode.Open, 
  28.                                    FileAccess.Read, FileShare.Read);
  29.           }
  30.           catch (Exception exc)
  31.           {
  32.                Console.WriteLine("HexDump: {0}", exc.Message);
  33.                return;
  34.           }
  35.           Console.WriteLine(strFileName);
  36.           DumpStream(fs);
  37.           fs.Close();
  38.      }
  39.      protected static void DumpStream(Stream stream)
  40.      {
  41.           byte[] abyBuffer = new byte[16];
  42.           long   lAddress  = 0;
  43.           int    iCount;
  44.  
  45.           while ((iCount = stream.Read(abyBuffer, 0, 16)) > 0)
  46.           {
  47.                Console.WriteLine(ComposeLine(lAddress, abyBuffer, iCount));
  48.                lAddress += 16;
  49.           }
  50.      }
  51.      public static string ComposeLine(long lAddress, byte[] abyBuffer, 
  52.                                       int iCount)
  53.      {
  54.           string str = String.Format("{0:X4}-{1:X4}  ",
  55.                               (uint) lAddress / 65536, (ushort) lAddress);
  56.  
  57.           for (int i = 0; i < 16; i++)
  58.           {
  59.                str += (i < iCount) ? 
  60.                               String.Format("{0:X2}", abyBuffer[i]) : "  ";
  61.                str += (i == 7 && iCount > 7) ? "-" : " ";
  62.           }
  63.           str += " ";
  64.  
  65.           for (int i = 0; i < 16; i++)
  66.           {
  67.                char ch = (i < iCount) ? Convert.ToChar(abyBuffer[i]) : ' ';
  68.                str += Char.IsControl(ch) ? "." : ch.ToString();
  69.           }
  70.           return str;
  71.      }
  72. }