using System;
using System.IO;
using System.Security.Cryptography;
namespace FileHashGenerator {
class Program {
static void Main( string[] args ) {
if( args.Length==0 ) {
PrintHelp();
}
else {
FileHashGeneratorInput programInput = new FileHashGeneratorInput(args);
SearchOption option = programInput.IsWithSubFolders ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
string[] files = programInput.Sourcetype==FileHashGeneratorInput.SourceType.File ? new[] {programInput.Source} : Directory.GetFiles(programInput.Source, "*.*", option);
using( TextWriter tw = programInput.Target=="" ? Console.Out : new StreamWriter(programInput.Target) ) {
foreach( string file in files ) {
tw.WriteLine(file+" : "+GenerateHash(file));
}
tw.Flush();
}
}
}
private static string GenerateHash(string fileName) {
try {
using( FileStream file = new FileStream(fileName, FileMode.Open) ) {
return Convert.ToBase64String(new MD5CryptoServiceProvider().ComputeHash(file));
}
}
catch( Exception e) {
return "Cannot generate hash for file ("+e.Message+")";
}
}
private static void PrintHelp() {
Console.WriteLine("\tGenerate MD5 hash string for a file.");
Console.WriteLine("FileHashGenerator.exe -source <filePath\\dirPath> [-target <outputFilePath>] [-withSubs]");
Console.WriteLine("-source : file or directory path");
Console.WriteLine("[-target] : file path to output data (by default Console.Out)");
Console.WriteLine("[-withSubs] : determines whether get hash from sub folders (works only if -source is folder)");
Console.WriteLine("Examples:");
Console.WriteLine(@"FileHashGenerator.exe -source c:\temp");
Console.WriteLine(@"FileHashGenerator.exe -source c:\temp\text.txt");
Console.WriteLine(@"FileHashGenerator.exe -source c:\temp -target c:\tempDirHash.txt -withSubs");
}
}
public class FileHashGeneratorInput {
public string Source { get; set; }
public string Target { get; set; }
public bool IsWithSubFolders { get; set; }
public SourceType Sourcetype { get; set; }
public FileHashGeneratorInput( string[] args ) {
try {
//TODO: refactor to CaseInsensetive
this.Source = args[Array.IndexOf(args, "-source")+1];
this.Target = Array.Find(args, s => s.ToLower()=="-target")!=null ? args[Array.IndexOf(args, "-target")+1] : "";
this.IsWithSubFolders = Array.Find(args, s => s.ToLower()=="-withsubs")!=null;
}
catch {
Console.WriteLine("Incorrect arguments");
}
this.Sourcetype = Directory.Exists(this.Source) ? SourceType.Folder : SourceType.File;
}
public enum SourceType {
File,
Folder
}
}
}
* This source code was highlighted with Source Code Highlighter.
пятница, 22 мая 2009 г.
File Hash Generator
Подписаться на:
Сообщения (Atom)