Search code examples
c#filefilesystemwatcher

FileSystemWatcher Onchage return value


I have a FileSystemEventHandler that onchange read the data from my file, now I need to return this data as I am working with a handler. now my code works but does not return anything so I do not have the updated data on my front end. this is my question : how can I return the data?

Thanks

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

Solution

  • FileSystemWatcher is an event-driven mechanism. You don't need to return anything from your Run() method - you need to do whatever you want to do as a result of the change in your OnChanged() event handler. Try taking a look at the API for FileSystemEventArgs.

    [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
    }