CSharp examples for File IO:File
loop through all of the files in a directory and perform a hex dump
using System;/*ww w. j a v a 2 s. c o m*/ using System.IO; public class Program { public static void Main(string[] args) { string directoryName = Directory.GetCurrentDirectory(); Console.WriteLine(directoryName); FileInfo[] files = GetFileList(directoryName); foreach(FileInfo file in files) { Console.WriteLine("\n\nhex dump of file {0}:", file.FullName); DumpHex(file); break; } Console.WriteLine("\no files left"); } public static FileInfo[] GetFileList(string directoryName) { FileInfo[] files = new FileInfo[0]; try { DirectoryInfo di = new DirectoryInfo(directoryName); files = di.GetFiles(); } catch(Exception e) { Console.WriteLine("Directory \" + directoryName" + "\" invalid"); Console.WriteLine(e.Message); } return files; } public static void DumpHex(FileInfo file) { FileStream fs; BinaryReader reader; try { fs = file.OpenRead(); reader = new BinaryReader(fs); } catch(Exception e) { Console.WriteLine("\ncan't read from \"" + file.FullName + "\""); Console.WriteLine(e.Message); return; } for(int line = 1; true; line++) { byte[] buffer = new byte[10]; int numBytes = reader.Read(buffer, 0, buffer.Length); if (numBytes == 0) { return; } Console.Write("{0:D3} - ", line); DumpBuffer(buffer, numBytes); if ((line % 20) == 0) { Console.WriteLine("Enter return to continue another 20 lines"); Console.ReadLine(); } } } public static void DumpBuffer(byte[] buffer, int numBytes) { for(int index = 0; index < numBytes; index++) { byte b = buffer[index]; Console.Write("{0:X2}, ", b); } Console.WriteLine(); } }