SHARE
TWEET

xmlHanler

sangueroots May 29th, 2018 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Configuration;
  7. using System.Xml;
  8. using System.IO;
  9.  
  10. namespace Movix.Robo
  11. {
  12.     public static class ConfigExtension
  13.     {
  14.         public static Configuration SetAppSetting(this Configuration config, string key, string value)
  15.         {
  16.             if (config == null) return config;
  17.  
  18.             var isAppSettingsExternalFile = !string.IsNullOrEmpty(config.AppSettings.File);
  19.  
  20.             if (isAppSettingsExternalFile){
  21.                 var dirConfig = Path.GetDirectoryName(config.AppSettings.File);
  22.                 if (string.IsNullOrEmpty(dirConfig)) dirConfig = Path.GetDirectoryName(config.FilePath);
  23.  
  24.                 string path = Path.Combine(dirConfig, Path.GetFileName(config.AppSettings.File));
  25.  
  26.                 XmlDocument doc = new XmlDocument();
  27.                 doc.Load(path);
  28.  
  29.                 XmlNode node = doc.SelectSingleNode("/appSettings/add[@key='"+key+"']");
  30.                 if (node == null){
  31.                     XmlElement elem = doc.CreateElement("add");
  32.  
  33.                     elem.SetAttribute("key", key);
  34.                     elem.SetAttribute("value", value);
  35.  
  36.                     doc.SelectSingleNode("/appSettings").AppendChild(elem);
  37.                 }else{
  38.                     node.Attributes["value"].Value = value;
  39.                 }
  40.  
  41.                 using (XmlTextWriter writer = new XmlTextWriter(path, Encoding.UTF8)){
  42.                     writer.Formatting = Formatting.Indented;
  43.                     doc.WriteTo(writer);
  44.                     writer.Flush();
  45.                     writer.Close();
  46.                 }
  47.             }else{
  48.                 AppSettingsSection appSettings = config.AppSettings;
  49.  
  50.                 if (appSettings.Settings[key] == null){
  51.                     appSettings.Settings.Add(new KeyValueConfigurationElement(key, value));
  52.                 }else{
  53.                     appSettings.Settings[key].Value = value;
  54.                 }
  55.  
  56.                 config.Save();
  57.             }
  58.  
  59.             ConfigurationManager.RefreshSection("appSettings");
  60.  
  61.             config = ConfigurationManager.OpenExeConfiguration(config.FilePath);
  62.  
  63.             return config;
  64.         }
  65.     }
  66. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top