简体   繁体   English

如何检查文件是否已在C#中修改

[英]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 . 有人建议使用FileInfo类,但它只为您提供lastWriteTimeLastAccessTimeCreationTime

I would like to use FileInfo class rather than FileSystemWatcher to check for modifications but how? 我想使用FileInfo类而不是FileSystemWatcher来检查修改,但是如何?

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. 示例:假设一个用户在我的程序中编辑了一个他们加载的文件,然后单击EXIT,我想要一种方法来检查是否对该文件进行了任何修改。 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... 最简单的方法是计算文件的MD5哈希值,并将其与原始MD5哈希值进行比较,如果这两个不匹配,则文件已被修改...

        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. 这是一些有关如何使用File或FileInfo类获取LastWriteTime的示例。

http://www.csharp-examples.net/file-creation-modification-time/ 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. 加载文件时,我将存储文件的时间戳,然后将其与File.GetLastWriteTime()进行比较,以查看此后是否已保存文件。 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. 如果文件是由外部来源修改的,则可以为用户提供放弃其更改并重新加载文件或将其更改保存到新文件的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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