简体   繁体   中英

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?

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();
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM