如何在其他循环函数中获取“ FileSystemWatcher”的值

时间:2019-12-26 08:03:15

标签: c# delegates

我有用于检测文件更改的“ SystemWatchFile”类。每个文件都已更改,因此我可以在函数“ OnChanged”中捕获此更改。 在其他循环功能中,我调用SystemWatchFile来监视文件的更改。如下所示:

       while (true)
        {
            SystemWatchFile watchfile = new SystemWatchFile(@" f:\Tutorial\C#\FileSytemWatcher\readme.txt");
            watchfile.Run();

            ///at here , how can i get value from "OnChanged" , when a file is changed
        }

我尝试使用委托来实现回调,但不起作用。我的课程:

public class SystemWatchFile
{
    string FileNeedWatching = "";
    bool let = false;
    public SystemWatchFile(string file)
    {
        FileNeedWatching = file;
    }
    public  void Run()
    {
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            string filePath1 = FileNeedWatching;
            watcher.Path = Path.GetDirectoryName(filePath1);
            // Watch for changes in LastAccess and LastWrite times, and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastAccess
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            // Only watch text files.
            watcher.Filter = Path.GetFileName(filePath1);
            // Add event handlers.
            watcher.Changed += OnChanged;
            // Begin watching.
            watcher.EnableRaisingEvents = true;

        }

    }
    private  void OnChanged(object source, FileSystemEventArgs e)
    {
        if (let == false)
        {
            Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
            let = true;
        }
        else
        {
            let = false;
        }            

    }
}

文件更改时如何获得价值?

0 个答案:

没有答案