如何使用C#3.5框架更新App.config?

| 如何通过C#代码在C#3.5 app.config文件或Settings.settings文件中更新? 请向我提供与C#3.5框架类支持有关的代码,但在更新app.config文件时不提供与2.0框架类有关的代码。     
已邀请:
我在一个项目上弄乱了这个问题,并决定根据情况使用我自己的简单xml配置文件。问题是app.config出于特定原因具有应用程序级别和用户级别设置。此处其他人提到的“代码项目”文章可以帮助您实现目标,但对我来说似乎是很多工作。 简单的方法,创建一个XML文件:
<?xml version=\"1.0\" encoding=\"utf-8\" ?>
<paths>
  <path name=\"pathtofile1\">
    <fullpath>\\\\machine1\\folder1\\file.txt</fullpath>
  </path>
  <path name=\"pathtofile2\">
    <fullpath>\\\\machine2\\folder2\\file2.txt</fullpath>
  </path>
</paths>
然后使用LINQ到达一个节点:
XDocument doc = XDocument.Load(pathToXmlfile);

var filePath1 = from c in doc.Descendants(\"path\")
                        where (string)c.Attribute(\"name\") == \"pathtofile1\"
                        select (string)c.Element(\"fullpath\").Value;

                string thePath = filePath1.First();
当然,您没有内置的类型,但这是一种简单,通用的方法,可以在很多情况下使用,例如在dll类中。 现在您正在使用\'regular \'xml文件,您可以使用此处提到的技术对其进行更新。例如,这个博客做得很好。     
这是一个xml文件,因此您可以使用linq来xml打开文件
var appConfigPath = string.Format(\"{0}{1}.exe.config\", Directory.GetCurrent(), Process.GetCurrentProcess().ProcessName);

var appConfig = XDocument.Parse(appConfigPath);

//have at it
    
可能的解决方案:在运行时更改App.config     
请检查以下代码: 您必须先加载web.congif:
System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"~\");
那么您可以像这样修改或添加它:
if (config.AppSettings.Settings[\"YourTag\"] == null)
            {
                config.AppSettings.Settings.Add(\"YourTag\", \"yourValue\");
            }
else
            {
                config.AppSettings.Settings[\"YourTag\"].Value = \"yourValue\";
            }
    

要回复问题请先登录注册