2

使用 C#,我可以检查文件是否被某个程序修改过, DateTime dt = File.GetLastWriteTime(filename);我最初只是存储这个时间,并每隔几秒钟将其与timer.Elapsed += OnTimedEvent;

我想知道是否有其他解决方案?某种事件处理程序,是否可以“监听”指定的文件并在 C# 中相应地运行一些代码?

4

3 回答 3

0

FileSystemWatcher可以在检测到文件系统更改时引发事件。

在您的情况下,听起来您想使用of订阅该Changed事件。NotifyFilterLastWrite

于 2019-01-30T11:32:03.437 回答
0

您可以使用 File​System​Watcher 定义文件更改事件。从 System.IO 更改以触发修改时的任何代码,因此您不必轮询它。

于 2019-01-30T11:32:29.960 回答
0

下面的代码仅处理指定文件夹中 txt 文件的更改,但这就是我所需要的。使用 csc.exe 编译,此代码有效。谢谢各位给我指点!

using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{
    public static void Main()
    {
    Run();
    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\somePath"; // set correct path
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.txt";  // watch for txt only
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
        while(Console.ReadLine()==null); // wait for keypress
    }
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }
}
于 2019-01-30T14:53:10.913 回答