简体   繁体   中英

ASP.NET FileSystemWatcher Changed Event

I created a ASP.NET Website with Visual Studio 2010 C#.

My program reads a config file to create some classes and display informations.

The config file is not included in the project (does not appear in the solution explorer). If I modify the file while my application is not running, and run it afterwards, it still reads the old version like it keep it in cache. I have to close Visual Studio for it to accept the changes.

My second problem is related to (if not caused by) my first problem. I am using FileSystemWatcher to see if the config file is modified while the application is running, but the Changed event is never called.

private string _configFilePath;
private FileSystemWatcher _watcher;

protected void Page_Load(object sender, EventArgs e)
{
    //Gets the config file in the application's parent directory
    string appPath = this.MapPath("~");
    string[] split = appPath.Split('\\');
    _configFilePath = appPath.Substring(0, appPath.Length - split[split.Length-1].Length);

    Application.Add("watcher", new FileSystemWatcher(_configFilePath.Substring(0, _configFilePath.Length-1), "*.xml"));
    _watcher = (FileSystemWatcher)Application["watcher"];
    _watcher.NotifyFilter = NotifyFilters.FileName;
    _watcher.Changed += new System.IO.FileSystemEventHandler(Watcher_Changed);

    _configFilePath += "ProductsConfig.xml";

    UpdateDisplay();
}

private void Watcher_Changed(object source, FileSystemEventArgs e)
{
    UpdateDisplay();
}

How can I solve this?

Thank you

My second problem is related to (if not caused by) my first problem. I am using FileSystemWatcher to see if the config file is modified while the application is running, but the Changed event is never called.

It's never called because at that point the Thread that's servicing the request is already returned to the pool and the request has ended. The Watcher_Changed event will never fire.

You need to tackle this in a different manner, remember that HTTP is a "disconnected" protocol, after the request has been served, don't expect any of the page events to fire "automagically" when something happens on the server side that would notify all connected users.

One way to do this is via Ajax. You'd need to constantly "ask" the server whether there's new information or not and update the sections of the page that need to be updated as a result of the change on the server.

There are 2 problems here. 1. You never called _watcher.EnableRaisingEvents = true; 2. You try to go to the parent folder of your root folder, which might not be allowed.

/ Tibi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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