skip to Main Content

I am looking for the fastest way (in C#/ASP.NET) to detect if anything inside a folder has changed between two points in time. I don’t need to know the files, total size, or anything else about the folder. I just need to know if anything has changed.

Because I do not have access to the outer scope in which such a folder change detection method would run, I cannot use FileSystemWatcher, which must be disposed when no longer needed (it implements IDisposable and due to the architecture of what I need I am unable to use it in a practical manner).

It would be ideal if there were some kind of "folder fingerprint" GUID that changed if the folder’s contents changed. I could then just compare the last fingerprint GUID to the current fingerprint and return true if the two fingerprints were different, indicating something has changed within the folder.

Ideally it would work exactly like the value returned by Assembly.GetEntryAssembly().ManifestModule.ModuleVersionId, which gives you a "fingerprint" GUID of your application’s current build, which then allows you to detect if your application has been recompiled between two points in time.

Something like this:

Note: "System.IO.GetFolderFingerprint()" is an imaginary method.

public static class FolderChangeChecker
{
    private const string _path = "c:/path/to/folder";    
    private static Guid _originalFingerprint = System.IO.GetFolderFingerprint(_path);    
    public static bool FolderHasChanged()
    {    
        return System.IO.GetFolderFingerprint(_path) != _originalFingerprint;
    }
}

Please let me know if there is a way to do this quickly.

2

Answers


  1. You could enumerate the files in the directory and build a big string made up of Files’ Name, Length, LastWriteTimeUtc.Ticks and create a Hash.

    fileStringSb = new StringBuilder();
    
    foreach (var file in files)
    {
        var fileInfo = new FileInfo(file);
    
        fileStringSb .Append(fileInfo.Name);
        fileStringSb .Append(fileInfo.Length.ToString());
        fileStringSb .Append(fileInfo.LastWriteTimeUtc.Ticks.ToString());
    }
    
    using (var md5 = System.Security.Cryptography.MD5.Create())
    {
        byte[] filesHash = fingerPrint = md5.ComputeHash(Encoding.UTF8.GetBytes(fileStringSb.ToString());
    }
    
    Login or Signup to reply.
  2. Advance logging IIS lets you record even file system events that you then can filter your log file for
    advance logging IIS

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search