How can I watch the user.config file and reload the settings when it changes?

后端 未结 3 786
深忆病人
深忆病人 2021-02-11 00:30

I have a situation where I am running multiple instances of my WPF application. I want the instances to share the same user.config file. Currently, whichever instance writes t

相关标签:
3条回答
  • 2021-02-11 00:58

    You should Cache the file and implement CacheDependency so that if any change is made to the file the file gets reloaded in the Cache. I am using a permission xml file in my application which gets stored in the cache and reloaded if file gets changed. Here's the code:

    protected void Page_Load(object sender, EventArgs e)
    {
            XmlDocument permissionsDoc = null;
    
            if (Cache["Permissions"] == null)
            {
                string path = Server.MapPath("~/XML/Permissions.xml");
                permissionsDoc = new XmlDocument();
                permissionsDoc.Load(Server.MapPath("~/XML/Permissions.xml"));
                Cache.Add("Permissions", permissionsDoc,
                                new CacheDependency(Server.MapPath("~/XML/Permissions.xml")),
                               Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                        CacheItemPriority.Default, new CacheItemRemovedCallback(ReloadPermissionsCallBack));
            }
            else
            {
                permissionsDoc = (XmlDocument)Cache["Permissions"];
            }
    }
    
    private void ReloadPermissionsCallBack(string key, object value, CacheItemRemovedReason reason)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Server.MapPath("~/XML/Permissions.xml"));
            Cache.Insert("Permissions", doc ,
                                new CacheDependency(Server.MapPath("~/XML/Permissions.xml")),
                               Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                        CacheItemPriority.Default, new CacheItemRemovedCallback(ReloadPermissionsCallBack));
        }
    

    Caching will also increase your application performance.

    0 讨论(0)
  • 2021-02-11 01:08

    I found it. The following code will return the path to the user.config file. You need to add a reference to System.Configuration.dll

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
    string path = config.FilePath;
    

    Now I can use a FileSystemWatcher to get notified when the file changes.

    0 讨论(0)
  • 2021-02-11 01:08

    could you use the fileSystemWatcher control?

    it has a modified event you can trigger

    0 讨论(0)
提交回复
热议问题