Created
August 13, 2020 09:04
-
-
Save TimGeyssens/9a3323808824f8c539e5c8d4b8653aed to your computer and use it in GitHub Desktop.
StaticFileHasher for c#
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Security.Cryptography; | |
using System.Text; | |
namespace MyUmbracWebsite | |
{ | |
public static class StaticFileHasher | |
{ | |
private static Dictionary<string, string> FileHashes { get; set; } | |
public static string Hash(string path) | |
{ | |
if (String.IsNullOrEmpty(path) || !FileHashes.ContainsKey(path)) | |
{ | |
return null; | |
} | |
return FileHashes[path]; | |
} | |
public static void HashFiles(params string[] directories) | |
{ | |
FileHashes = new Dictionary<string, string>(); | |
var FileExtensions = new string[] { "*.css", "*.js", }; | |
using (var md5 = MD5.Create()) | |
{ | |
foreach (var directory in directories) | |
{ | |
foreach (var extension in FileExtensions) | |
{ | |
foreach (var file in Directory.EnumerateFiles(directory, extension)) | |
{ | |
byte[] hash; | |
using (var stream = File.OpenRead(file)) | |
{ | |
hash = md5.ComputeHash(stream); | |
} | |
StringBuilder sOutput = new StringBuilder(hash.Length); | |
for (var i = 0; i < hash.Length - 1; i++) | |
{ | |
sOutput.Append(hash[i].ToString("X2")); | |
} | |
FileHashes.Add(Path.GetFileName(file), sOutput.ToString().ToLower()); | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment