cantfindaname88
cantfindaname88

Reputation: 315

How to check if a file has been modified in c#

I want to prompt a user to save a file when some modification has been done to it but the problem is i can't for the life of me do that.

Some people have suggested using FileInfo class but it only gives you the lastWriteTime, LastAccessTime and CreationTime.

I would like to use FileInfo class rather than FileSystemWatcher to check for modifications but how?

Example: Say a user has edited a file, within my program, that they loaded and clicks EXIT, i want a way to check whether any modifications were done on the file. If none, exit. If some, prompt user to save the file. So how do i check for modifications on that FILE?

Upvotes: 2

Views: 9829

Answers (2)

mgnoonan
mgnoonan

Reputation: 7200

Here are some examples of how to use the File or FileInfo class to get the LastWriteTime.

http://www.csharp-examples.net/file-creation-modification-time/

I would store the timestamp of the file when you load it, then compare it to the File.GetLastWriteTime() to see if the file has been saved since then. If the file was modified by an outside source, you can give the user the option to discard their changes and reload the file, or save their changes to a new file.

Upvotes: 1

Dean Kuga
Dean Kuga

Reputation: 12131

The easiest way is to calculate the MD5 hash of the file and compare to the original MD5 hash and if these two don't match the file was modified...

        using (var md5 = new MD5CryptoServiceProvider())
        {
            var buffer = md5.ComputeHash(File.ReadAllBytes(filename));
            var sb = new StringBuilder();
            for (var i = 0; i < buffer.Length; i++)
            {
                sb.Append(buffer[i].ToString("x2"));
            }
            return sb.ToString();
        }

Upvotes: 7

Related Questions