开发者

How to update App.config using C#3.5 framework?

开发者 https://www.devze.com 2023-02-24 11:39 出处:网络
How to update in C#3.5 app.config file or Settings.settings file through C# code? Please provide me the code related to C#3.5 framework support of classes but not with 2.0 framework classes in updati

How to update in C#3.5 app.config file or Settings.settings file through C# code?

Please provide me the code related to C#3.5 framework support of classes but not with 2.0 framework classes in updating app.c开发者_Python百科onfig file.


I messed with this issue on a project, and decided depending on circumstance to just use a simple XML config file of my own. The problem is app.config has application level and user level settings for a specific reason. The Code Project article mentioned by others here can get you there, but seems like a lot of work to me.

Easy way, create an XML file:

<?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>

then use LINQ to get at a node:

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();

Of course you don't have the built in typing, but this is an easy, generic approach you can use in a lot of situations such as in dll classes.

Now that you are using a 'regular' xml file, you can use the techniques mentioned here to update it. For example and this blog does a nice job.


Possible solution: Changing App.config at Runtime


Please check out this code:

You have to load the web.congif first:

System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

Then you can modify or add it just like this:

if (config.AppSettings.Settings["YourTag"] == null)
{
    config.AppSettings.Settings.Add("YourTag", "yourValue");
}
else
{
    config.AppSettings.Settings["YourTag"].Value = "yourValue";
}


It's an XML file so you can use LINQ to XML to open the file

var appConfigPath = string.Format("{0}{1}.exe.config", Directory.GetCurrent(), Process.GetCurrentProcess().ProcessName);

var appConfig = XDocument.Parse(appConfigPath);

//have at it


XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load("..\\App.config");

XmlNode node = xmlDoc.SelectSingleNode("configuration/capabilities/single/add");// pass xpath of node
//node.Attributes[1].Value = MethodBase.GetCurrentMethod().Name;
node.Attributes[1].Value = TestContext.CurrentContext.Test.MethodName;

xmlDoc.Save("..\\App.config");

Please write in main methods, it is working for me.

0

精彩评论

暂无评论...
验证码 换一张
取 消