Wednesday, July 11, 2007

How To: update within app.config file a key

today I had the pleasure to write a Setup for my project indeXus.Net Shared Cache (available on Codeplex). While others will install this WinService on various Hosts I needed a way how I can take the administration effort from the user.

In my case I had to update an appSettings Key within various *.config files and backup them into an Application Data Folder.

The solution seems to be very easy after I found all tricks....

15 static string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace(@"file:\", "");
16 static string appPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\MergeSystem\backup";

(thanks here to atif) some more coding between....

70 ///


71 /// Evaluates the and update machine IP within all Config files
72 ///

73 private static void EvaluateAndUpdateMachineIP()
74 {
75 IPHostEntry localMachineInfo = Dns.GetHostEntry(Dns.GetHostName());
76 DirectoryInfo dir = new DirectoryInfo(path);
77 foreach (FileInfo fi in dir.GetFiles("*.config"))
78 {
79 ExeConfigurationFileMap map = new ExeConfigurationFileMap();
80 map.ExeConfigFilename = fi.Name;
81
82 //Configuration config = ConfigurationManager.OpenExeConfiguration(fi.FullName);
83 Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
84 if(config.AppSettings != null && config.AppSettings.Settings != null)
85 {
86 if(config.AppSettings.Settings[WinServiceCommon.Constants.ConfigServiceCacheIpAddress] != null)
87 {
88 config.AppSettings.Settings[WinServiceCommon.Constants.ConfigServiceCacheIpAddress].Value = localMachineInfo.AddressList[0].ToString();
89 config.Save(ConfigurationSaveMode.Modified);
90 ConfigurationManager.RefreshSection("appSettings");
91 }
92 }
93 }
94 }

No comments:

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge