/// <summary> /// Generates a signature for a given file path. /// </summary> /// <param name="path">The path for which to generate a signature.</param> /// <returns>A <see cref="Checksum.FileSignature"/> object containing the size and a set of hashes for the input path.</returns> private static FileSignature CreateFileSignature(string path) { FileSignature signature = default(FileSignature); try { byte[] contents = File.ReadAllBytes(path); signature = new FileSignature(path, contents.Length, new Dictionary <string, byte[]> { { "MD5", CalculateFileHash(contents, HashProviderMd5) }, { "SHA1", CalculateFileHash(contents, HashProviderSha1) }, { "SHA256", CalculateFileHash(contents, HashProviderSha256) }, { "SHA512", CalculateFileHash(contents, HashProviderSha512) } }); } catch (FileNotFoundException) { DisplayError($"File not found. ({path})"); } catch (DirectoryNotFoundException) { DisplayError($"Directory not found. ({path})"); } catch (PathTooLongException) { DisplayError($"File path exceeds maximum length. ({path})"); } catch (UnauthorizedAccessException) { DisplayError($"File access permission denied. ({path})"); } return(signature); }
/// <summary> /// Writes a formatted file signature to a given <see cref="System.IO.TextWriter"/> /// </summary> /// <param name="signature">The file signature to display.</param> /// <param name="writer">The <see cref="System.IO.TextWriter"/> to use.</param> private static void WriteSignature(FileSignature signature, TextWriter writer) { writer.WriteLine($"\"{signature.Path}\" ({signature.Size:n0} bytes)"); foreach (string hash in signature.Hashes.Keys) { writer.WriteLine($" {hash,-10}{FormatHash(signature.Hashes[hash])}"); } }
public static void Main(string[] args) { if (args.Length == 0) { DisplayHelpText(); return; } _commandLine = ParseCommandLineArguments(args); string outputPath = _commandLine.OutputPath; using (var output = new StreamWriter(File.Create(outputPath ?? DefaultOutputFilename))) { foreach (string path in _commandLine.InputPaths) { if (IsDirectory(path)) { // Directories are currently unsupported. // In future, directories will be traversed and signatures will be produced for each file in the tree DisplayError("Directories are currently unsupported."); continue; } FileSignature currentSignature = CreateFileSignature(path); if (!_commandLine.SuppressConsoleOutput) { DisplaySignature(currentSignature); } if (!_commandLine.SuppressFileOutput) { WriteSignature(currentSignature, output); } } } }
/// <summary> /// Writes a formatted file signature to <see cref="System.Console"/>. /// </summary> /// <param name="signature">The file signature to display.</param> private static void DisplaySignature(FileSignature signature) => WriteSignature(signature, Console.Out);