FileSystemWatcher更改返回值

本文关键字:返回值 FileSystemWatcher | 更新日期: 2023-09-27 18:15:45

我有一个FileSystemEventHandler, onchange从我的文件中读取数据,现在我需要返回这个数据,因为我正在使用处理程序。现在我的代码工作,但不返回任何东西,所以我没有更新的数据在我的前端。这是我的问题:我如何才能返回data ?

感谢
public static string data = null;
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static string Run()
{
    try
    {
        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        //watcher.Path = System.IO.Directory.GetCurrentDirectory();
        watcher.Path = Path.Combine(HttpRuntime.AppDomainAppPath, "view");
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "info.txt";
        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        // Begin watching.
        watcher.EnableRaisingEvents = true;
    }
    catch (Exception ex)
    {
        Console.Write(ex.ToString());
    }
    return data;
}
private static void OnChanged(object source, FileSystemEventArgs e)
{
    data = FileManager.Read();
}

FileSystemWatcher更改返回值

FileSystemWatcher是事件驱动机制。您不需要从Run()方法返回任何东西-您需要做任何您想做的事情,因为您的OnChanged()事件处理程序发生了变化。试着看看FileSystemEventArgs的API。

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
    try
    {
        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        //watcher.Path = System.IO.Directory.GetCurrentDirectory();
        watcher.Path = Path.Combine(HttpRuntime.AppDomainAppPath, "view");
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "info.txt";
        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        // Begin watching.
        watcher.EnableRaisingEvents = true;
    }
    catch (Exception ex)
    {
        Console.Write(ex.ToString());
    }
}

private static void OnChanged(object source, FileSystemEventArgs e)
{
    string fileText = File.ReadAllText(e.FullPath);
    // do whatever you want to do with fileText
}