RSS 2.0 Feed
RSS 2.0


Atom 1.0 Feed
Atom 1.0

  Writing to Your .NET Application's Config File 


qt8gt0bxhw|20009F4EEE83|RyanMain|subtext_Content|Text|0xfbffdc0000000000b100000001000400

There's likely been times that you might have thought that it would make things convenient to write back to your .NET application's config file. The framework provides simple methods for reading from the config file, but gives you nothing for writing values back to the config file. It is easy enough to write values back to the file. It's only XML. When I need to do this sort of thing I use a class that wraps up the ability to read and write settings in the config file.

Warning: As a rule of thumb, it is not good to write back to the config file. The framework does not include this ability for a reason. If you want your application's users to not require administrative rights then it is always a better idea to store settings in the user's documents & settings directory or in the registry if needed. That said, this won't break anything and does come in handy for utility applications etc.

OK, let's move on. A config file for a .NET application is a text file that has a name of myapplication.exe.config. The VS.NET IDE makes things easy for you and allows you to add a file named “App.config” to your project and it will copy it to the appropriate bin directory and rename it to myapplication.exe.config. This config file is intended to store static values or settings for your application. As I mentioned before, it is nothing more than XML. Here's a sample of an application config file:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="Test1" value="My value 1" />
        <add key="Test2" value="Another value 2" />
    </appSettings>
</configuration>


The framework make life simple to read those values. The ConfigurationSettings class in the System.Configuration namespace includes the static AppSettings property which returns a NameValueCollection of name/value pairs. To read the value for the “Test1” setting you can do this:


string test1 = ConfigurationSettings.AppSettings["Test1"];


Easy enough, right? One thing to note is that this will allow you to read settings from the appSettings section only. If you add other sections then you won't be able to read them this way (that's coming in a future post). But as the title of this post indicates, what I really wanted to talk about is how you can write settings back to the config file. Let's move on to that.

To write values back, you just need to open the config file as an XmlDocument and write away. No big deal. You can add name/value pairs, remove elements, modify them or whatever. And because I am tired of typing (and my wife is waiting for me to start a movie), let's just cut to the code. This class will allow you to read, write, and remove settings from the appSettings section of the config file based on the key or name of the setting.


using System;
using System.Xml;  
using System.Configuration;
using System.Reflection;
//...


public class ConfigSettings
{
    private ConfigSettings() {}

    public static string ReadSetting(string key)
    {
        return ConfigurationSettings.AppSettings[key];
    }

    public static void WriteSetting(string key, string value)
    {
        // load config document for current assembly
        XmlDocument doc = loadConfigDocument();

        // retrieve appSettings node
        XmlNode node =  doc.SelectSingleNode("//appSettings");

        if (node == null)
            throw new InvalidOperationException("appSettings section not found in config file.");

        try
        {
            // select the 'add' element that contains the key
            XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));

            if (elem != null)
            {
                // add value for key
                elem.SetAttribute("value", value);
            }
            else
            {
                // key was not found so create the 'add' element 
                // and set it's key/value attributes 
                elem = doc.CreateElement("add");
                elem.SetAttribute("key", key);
                elem.SetAttribute("value", value); 
                node.AppendChild(elem);
            }
            doc.Save(getConfigFilePath());
        }
        catch
        {
            throw;
        }
    }

    public static void RemoveSetting(string key)
    {
        // load config document for current assembly
        XmlDocument doc = loadConfigDocument();

        // retrieve appSettings node
        XmlNode node =  doc.SelectSingleNode("//appSettings");

        try
        {
            if (node == null)
                throw new InvalidOperationException("appSettings section not found in config file.");
            else
            {
                // remove 'add' element with coresponding key
                node.RemoveChild(node.SelectSingleNode(string.Format("//add[@key='{0}']", key)));
                doc.Save(getConfigFilePath());
            }
        }
        catch (NullReferenceException e)
        {
            throw new Exception(string.Format("The key {0} does not exist.", key), e);
        }
    }

    private static XmlDocument loadConfigDocument()
    {
        XmlDocument doc = null;
        try
        {
            doc = new XmlDocument();
            doc.Load(getConfigFilePath());
            return doc;
        }
        catch (System.IO.FileNotFoundException e)
        {
            throw new Exception("No configuration file found.", e);
        }
    }

    private static string getConfigFilePath()
    {
        return Assembly.GetExecutingAssembly().Location + ".config";
    }
}


So now to use it, you just use the static methods provided in the class like this:


// read the Test1 value from the config file
string test1 = ConfigSettings.ReadSetting("Test1");

// write a new value for the Test1 setting
ConfigSettings.WriteSetting("Test1", "This is my new value");

// remove the Test1 setting from the config file
ConfigSettings.RemoveSetting("Test1");


Now, before you get carried away, a few things to be aware of. First, this was written to work for config files for windows applications. If you wanted to use this for a web application's config file you'd change the private static method that returns the name/location of the config file to something like this:

System.Web.HttpContext.Current.Server.MapPath("web.config");

You'd also need to make sure the ASP.NET process user account had access to write to that directory. I'd avoid doing this anyway, but still wanted to point this out.

Note: Milan Negovan pointed out another strong word of caution in the comments about editing the web.config file for a web application and I thought it was worth adding it to the post so it wouldn't be missed. Every time you touch the web.config file the web app will recycle. Doing this often will throw performance out the window.

Second, if you wanted to put this class into it's own assembly/dll so you could reuse it easier, beware that this class get's the path of the config file based on the location of the executing assembly. So if this is in a DLL, it will be looking for a config file for the DLL, not the application using the class. In those cases you'd be better off passing in a reference to the assembly that you want to read/write config values for, or just pass in it's path or something. Got it?

All in all, an easy way to store configuration settings for your application. But heed my earlier warning. If your application is used by users in an AD, then you don't want to have to give them elevated rights just to write back to your applications directory under Program Files. That's what the Application Data directory is for under the users folder in Documents and Settings. Use it.




                   



Leave a comment below.

Comments

  1. Milan Negovan 7/14/2004 6:55 AM
    Gravatar
    A very interesting read, Ryan! I'd like to add a word of caution about writing to web.config: every time you touch it the web app recycles. If you do it often, you can forget about performance. :)
  2. Ryan Farley 7/14/2004 7:51 AM
    Gravatar
    Great point, Milan. I stay away from that kind of thing anyway. For a web app, it doesn't make sense to do this, it would be bad design IMO. But you raise an important enough point that I'm going to add your warning in the actual post so it doesn't get lost in the comments.

    Thanks, Ryan.
  3. Nick Parker 7/22/2004 7:47 AM
    Gravatar
    I actually wrote a similar concept a quite while back and posted an article covering it at The Code Project (http://www.codeproject.com/csharp/config_settings.asp). Visual Studio 2005 is going to make storing this type of information a lot easier.
  4. S 10/20/2004 5:49 PM
    Gravatar
    Once again, straight to the case. Excellent stuff!
  5. Sabah Tahir 11/26/2004 2:22 AM
    Gravatar
    Great work Ryan
  6. WTG!!! 12/12/2004 11:05 PM
    Gravatar
    WAY TO GO RYAN!
  7. Aymerick Troubat 12/21/2004 2:08 AM
    Gravatar
    Hello, i put this class in a dll.

    I could load my settings but not save them. I had an exception that tell me that the file was not found.

    Because getConfigFilePath() returns a name based on the executing assembly one which is my dll.

    So i fixed it like this :

    private static string getConfigFilePath()
    {
    return AppDomain.CurrentDomain.GetDat("APP_CONFIG_FILE").ToString ();
    }

    Otherwise, good job
  8. aymerick troubat 12/21/2004 3:00 AM
    Gravatar
    ooopsss....

    i made a typing error :

    private static string getConfigFilePath()
    {
    return AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
    }
  9. Ryan Farley 12/21/2004 10:39 AM
    Gravatar
    Thanks for the tip Aymerick.

    -Ryan
  10. Joe 12/27/2004 12:35 PM
    Gravatar
    This may seem like a stupid question but how do you get this to write straight to the app.config file in your project?
  11. Ryan Farley 12/27/2004 12:46 PM
    Gravatar
    Hi Joe,

    Not sure I follow the question. What this code does is provide a class that can be used at runtime to write (and read) values to the application's config file. This does not do anything to write to the app.config that is part of your project in Visual Studio, this is a class to change that at runtime for a deplyed application. Could you restate the question?

    Thanks,
    Ryan
  12. Al 12/28/2004 11:34 AM
    Gravatar
    Alright,
    now I am curious can you write back to a "local.config" files appsettings if you are using


    appSettings file = "local.config"

    in your current exe.config file
  13. KMO 1/17/2005 4:46 AM
    Gravatar
    Another note to web.config. Every time the web app recycles you also loose all current application varaibles and sessions.

    And Joe, the app.config is a file created by Visual Studio and it is copied into <application name>.exe.config every time you start the application from Visual Studio..
  14. Sailaja V 2/9/2005 12:52 AM
    Gravatar
    Hi,

    code is very nice and great....its working properly when i gave my local file path

    private static string getConfigFilePath()
    {
    return C:\\WorkingFolder\\App.config;
    }
    but how to get that file name without giving static string like above ....
    private static string getConfigFilePath()
    {
    return Assembly.GetExecutingAssembly().Location + ".config";
    }
  15. Mike C 2/15/2005 6:06 AM
    Gravatar
    Ryan, AWESOME code, this is EXACTLY what I have been looking for. Thanks again!
  16. Ryan Farley 2/15/2005 9:05 AM
    Gravatar
    Sailaja V,

    Are you saying that Assembly.GetExecutingAssembly().Location + ".config" is not returning the path to the config file for you? I assume you're working with a windows app (ie: not web), right? What kind of app is it (ie: exe, dll, service)?

    -Ryan
  17. rekha 2/18/2005 11:24 AM
    Gravatar
    In Windows forms using vb.net, Can you tell me how to read values from a section other than appsettings. You did say there would be a future post... thanks
  18. Andrew H 3/7/2005 4:50 PM
    Gravatar
    This is all fine and good, but, note that the appSettings are not actually refreshed at runtime if you refer back to the System.Configuration.ConfigurationSettings.AppSettings collection.
  19. Ryan Farley 3/7/2005 7:39 PM
    Gravatar
    Andrew, excellent point. Thanks for mentioning that. You know I had not even thought of that one since usually this kind of thing is a "read on load, write on exit" sort of thing.

    Thanks,

    -Ryan
  20. Steffen J 3/20/2005 11:39 PM
    Gravatar
    This is really great, but is there a way to 'refresh' to be able to read the new settings at runtime?
    Thanks,
    Steffen J
  21. Ryan Farley 3/21/2005 6:37 AM
    Gravatar
    Steffen,

    No way to cause it to reload the config settings that I know of. I would just suggest to do away with ConfigurationSettings.AppSettings and just read the XML yourself. And since you're doing that (both reading and writing the XML) you might as well just use an outside XML file for your configuration (which really is the route I usually go anyway).

    -Ryan
  22. Tony 3/22/2005 10:28 PM
    Gravatar
    Since this isn't a dead discussion, I'll toss in a few notes. I'm trying to get a runtime refresh of the exe.config as well, to dynamically change the behavior of Windows Service which periodically polls for new params. Well, there goes that idea. :)

    For anyone else searching for info on how to find the config file, it's amazing how much wrong info is out on the net. With myAssy defined as a string, the solution presented by Aymerick was the best:

    myAssy = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
    if (System.IO.File.Exists(myAssy)) { doLog = System.Configuration.ConfigurationSettings.AppSettings["log"]; }

    I strongly advise try/catch blocks around each critical statement, it might just be my box but the call to AppSettings goes to lunch and doesn't seem to come back unless it's in a Try. Weird...

    Here are 3 other ways of getting to config that DO NOT work for this purpose! :

    1) myAssy = System.Reflection.Assembly.GetExecutingAssembly().ToString() + ".exe.config";

    2) myAssy = this.ServiceName + ".exe.config";

    3) // two lines:
    myAssy = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
    myAssy += @"\" + System.IO.Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + ".config";

    Anyway - school of hard knocks... Now to go find or write a custom config R/W config file that isn't cached. :)
  23. M. Katz 3/25/2005 2:07 PM
    Gravatar
    Can anyone explain this - I made a standalone executable with VB.NET. called uploader.exe If I create the file uploader.exe.config and place it in the same directory where Visual Studio outputs the compiled EXE, and run the EXE in that directory, everything is fine. However, if I move everything to a different pathname, even though the .exe and the .config file continue to be located in the same directory, the application does not pick up the settings in the .config file. Help!
  24. Danel Richards 4/24/2005 12:00 AM
    Gravatar
    Hey, just wondering, am I allowed to use this code in an app I'm writing where i'll be giving out the code under an open source/public domain license?
    (With say, a link to this page saying this is where it's from/etc)
  25. Dan Osborne 5/11/2005 3:10 AM
    Gravatar
    Neat but does anyone know how to expand this to include other sections - I can't seem to find the future post referred to where this was to be addressed.

    Dan
  26. R 5/18/2005 6:56 AM
    Gravatar
    Awesome! Thanks!
  27. JAG 5/18/2005 7:18 PM
    Gravatar
    If you are using this class in a dll and replacing Assembly.GetExecutingAssembly().Location + ".config";
    in the getConfigFilePath() method.

    Its a little better than
    AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
    to use:
    AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

    Both return identical strings. I just think the second one is easier to remember and there's less chamce for a typo.
  28. ward0093 5/29/2005 9:21 AM
    Gravatar
    Just curious....

    Can you someway... somehow... have multiple applications (test1.exe & test2.exe) use the same .exe.config file?
  29. Redrat 6/7/2005 11:27 PM
    Gravatar
    Yes, a good question. Havnt myself found any way, but are considering how this should be done.

    Anyone knows how to have multiple applications and use the same config file? I guess one can write a class to handle it.
  30. Ryan Farley 6/13/2005 4:02 PM
    Gravatar
    ward0093,

    No. Instead of using a config file, you would want to use a standard XML file that all apps can read (I suppose you could read the other apps config file as an XML file, but I'd just use a XML file that is shared between apps rather than use a config file)

    -Ryan
  31. Pal Subramaniam 6/23/2005 1:03 PM
    Gravatar
    Very useful and functional class. Great work.
  32. Clarke Scott 7/3/2005 7:12 PM
    Gravatar
    Thanks
  33. Nithin Paul 7/11/2005 4:28 AM
    Gravatar
    Hey that was a neat bit a code,
    But let me know how can the path of the Web.config file extracted in the
    GetConfigDocumentPath() method ?
    Instead a just setting the path of the file as
    @"d:\inetpub\wwwroot\AntiVirusUpdateClone\Web.config"
    what method can be used to set the path ?
  34. Dillon 7/17/2005 8:33 PM
    Gravatar
    Hi Ryan,

    Great work! Thanks for sharing the code.
  35. Ryan Farley 7/18/2005 2:19 PM
    Gravatar
    Nithin,

    I'd caution you against writting to the config file in a web app altogether. Your app will essentially recompile/recycles after any change to the config file is made which invalidates the cache as well as makes for a very slow performing site. In a windows app (which is what I intended the code for in the first place) the same applies, but there are some valid uses for something like this that would make it OK in my opinion for some utility & small apps.

    -Ryan
  36. Ed Zehoo 7/20/2005 11:47 PM
    Gravatar
    Great work, Ryan

    Here's the VB.NET version of your code. Figured maybe I could save someone from all the typing.. :-)

    Regards,
    Ed


    Imports System
    Imports System.Xml
    Imports System.Configuration
    Imports System.Reflection

    Public Class ConfigSettings
    Public Shared Function ReadSetting(ByVal key As String) As String
    Return ConfigurationSettings.AppSettings(key)
    End Function

    Public Shared Sub WriteSetting(ByVal key As String, ByVal value As String)
    Dim doc As XmlDocument
    Dim node As XmlNode
    doc = loadConfigDocument

    'retrieve appSettings node
    node = doc.SelectSingleNode("//appSettings")

    If node Is Nothing Then
    MsgBox("Could not find <appSettings> section in the app.config file", MsgBoxStyle.Exclamation, "Section Missing")
    Else
    Dim elem As XmlElement
    'select the 'add' element that contains the key
    elem = node.SelectSingleNode(Format("//add[@key='{0}']", key))

    If elem Is Nothing = False Then
    'add value for key
    elem.SetAttribute("value", value)
    Else
    'key was not found so create the 'add' element
    'and set it's key/value attributes
    elem = doc.CreateElement("add")
    elem.SetAttribute("key", key)
    elem.SetAttribute("value", value)
    node.AppendChild(elem)
    End If
    doc.Save(getConfigFilePath())
    End If
    End Sub

    Public Shared Sub RemoveSetting(ByVal key As String)
    'load config document for current assembly
    Dim doc As XmlDocument
    Dim node As XmlNode
    doc = loadConfigDocument()

    'retrieve appSettings node
    node = doc.SelectSingleNode("//appSettings")
    If node Is Nothing Then
    MsgBox("Could not find <appSettings> section in the app.config file", MsgBoxStyle.Exclamation, "Section Missing")
    Else
    'remove 'add' element with coresponding key
    On Error GoTo errError
    node.RemoveChild(node.SelectSingleNode(Format("//add[@key='{0}']", key)))
    doc.Save(getConfigFilePath())
    End If
    Exit Sub
    errError:
    Msgbox("The key [" + key + "] does not exist")
    End Sub


    Public Shared Function loadConfigDocument() As XmlDocument
    Dim doc As XmlDocument
    doc = Nothing
    On Error GoTo errLoad
    doc = New XmlDocument
    doc.Load(getConfigFilePath())
    Return doc
    Exit Function
    errLoad:
    MsgBox("No configuration File Found", MsgBoxStyle.Exclamation, "File Missing")
    End Function

    Private Shared Function getConfigFilePath() As String
    Return [Assembly].GetExecutingAssembly.Location + ".config"
    End Function
    End Class
  37. ledeut 7/23/2005 3:41 AM
    Gravatar
    Is there a chance Mircosoft will some day implement a WriteConfig-Method? :/
  38. Swami 7/26/2005 12:25 PM
    Gravatar
    Question:

    Apparently, writing to the config file at runtime updates the Application.exe.config file, and not the App.config file which can be seen in the Solution Explorer. As a result ConfigurationSettings.AppSettings[x] doesn't return the updated value...how do I then retrieve the updated value from the Application.exe.config file?

    Thanks!
  39. Ryan Farley 7/26/2005 12:44 PM
    Gravatar
    Swami,

    The App.config file is simply a design-time thing. When you run your project, the App.config file is copied to the appropriate bin folder (Debug/Release/etc) as appname.exe.config. This is the file that the code will write to since as far as the app is concerned it *is* the one and only config file. It knows nothing of the app.config that is part of your solution. None of this matters outside of VS.NET. When you deply the application, you do not have an app.config file, only the appname.exe.config file. So it should be the only one you want to worry about.

    -Ryan
  40. Swami 7/26/2005 1:20 PM
    Gravatar
    Thanks Ryan. However, for testing purposes, I was wondering if there is anyway I can retrive the updated config value when I run the app from Visual Studio...

  41. Arun Mishra 7/27/2005 12:50 AM
    Gravatar
    Ryan, vs.net 2005 is probably providing methods to update the App.config file and refresh it value dynamically.
  42. Ryan Farley 7/27/2005 8:31 AM
    Gravatar
    Arun,

    I believe so. The ConfigurationSettings.AppSettings property is obsolete in .NET 2.0. You can now use the ConfigurationManager class. It has methods to open the config file for the app as a Configuration object (or you can even open the machine config). You can save the configuration and refresh it (reread from disk). You can access collections of all sections in the configuration and get the elements of the sections. Once you have the ConfigurationElement, I believe you can change it's value (or create a new ConfigurationElement to add so the configuration).

    However, I've not yet looked into how changing the configuration at runtime effects the performance of the app. I assume that changes to the configuration still causes the app to recycle, but I have not yet tested that.

    -Ryan
  43. Azam Farooq 7/27/2005 8:50 AM
    Gravatar
    I would like to incquire,that how am i suppose to add a certain key/value collection to the web.config file of an asp.net web application during its deployment?

    I have a custom action that takes certain inputs from the user during the setup. These parameters are Database server name, Database name, user name, etc. I need these values, along with their keys to be written in the web.config, as the application reads these values from there.

    Could anyone please guide me here?

    thanx in advance
  44. Ryan Farley 7/27/2005 9:07 AM
    Gravatar
    Azam,

    You will essentially open the config file as an XML file and write to it as needed. The code in this post does just that. The only difference from teh code above is that you will open the config file you wish to edit instead of the config file for the current app. In the code above, all you would change is the getConfigFilePath method to return the path to the other config file. You'd also need to change the ReadSetting method to read the values via XML instead of using the ConfigurationSettings class.

    -Ryan
  45. Azam 7/28/2005 12:57 AM
    Gravatar
    thanx for your help Ryan!
  46. Swami 8/10/2005 9:22 AM
    Gravatar
    Let's say, I have 2 projects in a solution, and I want to have only one config file that both projects can access. Is this possible? Is there a way for a class in one project to access an XML file in another?

    Thanks!

  47. southbaywear 8/14/2005 11:49 AM
    Gravatar
    When i start windows XP A error Reads>could not locate the application configuration file>ventcfg >does this sisuation apply to this subject ? or in a different matter ?Please reply.
  48. Ryan Farley 8/14/2005 4:54 PM
    Gravatar
    southbaywear, Different topic entirely. -Ryan
  49. Avadhoot 8/23/2005 11:11 PM
    Gravatar
    Thanks Ryan, for the superb information. This was exactly what i needed. Thank you very much.
  50. Armoghan 8/24/2005 9:33 PM
    Gravatar
    It it just writing to the XML but not updating the
    ConfigurationSettings.AppSettings


    So if I do

    Dim str As String = ConfigSettings.ReadSetting("Path")
    MessageBox.Show("Settings Before -> " & str)
    ConfigSettings.WriteSetting("Path", str.Replace("http://localhost/", txtPath.Text))
    MessageBox.Show("Settings Now ->" & ConfigSettings.ReadSetting("WinUI.WSLogin.Login"))


    I still get the old values

    Does any one know any solution for it. using VS.NET 2003
  51. Armoghan 8/24/2005 9:34 PM
    Gravatar
    Sorry Typo

    WinUI.WSLogin.Login = Path
  52. Sammy 8/26/2005 7:03 AM
    Gravatar
    Getting the same problem as Armoghan

    ConfigSettings.WriteSetting writes correctly to the config file but
    when you read after writing i get the old value instead of the newly
    written value.

    Any Idea
    Thanks
  53. Ryan Farley 8/26/2005 7:45 AM
    Gravatar
    Armoghan & Sammy,

    That is correct. When a .NET assembly loads it caches the configuration settings in the config file, since the code reads the values using the standard ConfigurationSettings.AppSettings[key]; these settings will only reflect what the values were when the app first loaded.

    How I typically use this is when my app loads I read all the values into memory and keep them there while the app is running. As the user changes settings I make the changes to the in-memory settings. Then when the app closes I write everything back to the config file. It all works fine that way.

    If you need to be able to write to the file and then read the new values back out at runtime, then you'd need to change the "ReadSetting" method to simply open the file as XML and read it out (similar to what the WriteSetting method is doing). Then you'd be able to read the changed values without problem.

    -Ryan
  54. Marc Tompkins 8/28/2005 1:42 PM
    Gravatar
    I seem to have done something very foolish... I'm finally getting into .NET using the 2005 Beta 2. (I actually bought VS.NET twice before, but never got around to using it - too much legacy stuff to do, you know?)

    Anyway, I'm writing my very first C# project, and I'm beating my head on something that used to be ridiculously simple: my user needs to select three paths/filenames, and I want to persist them. Easy, right? NOOOOOOO!!!!

    Settings used to be of the format
    <add key="foo" value="bar" />
    Now they are of the format
    <setting name="foo" serializeAs="String">
    <value "bar" />
    </setting>

    I imported your class (thank you, by the way), updated from deprecated ConfigurationSettings to ConfigurationManager, changed "appSettings" to "applicationSettings", changed "add" to "setting", "key" to "name"... but what I don't know how to do is save "value" as a child node instead of an attribute. When I try to save my settings, I end up with:
    <setting name="foo" serializeAs="String" value="bar">
    <value />
    </setting>
    which doesn't work.

    The answer is going to be very simple, and I will feel like an idiot... but not worse than I do now.

    TIA for any pointers!
  55. Sammy 8/29/2005 4:22 AM
    Gravatar
    Thanks Ryan,
    Thank you for your accurate explanation. I solved the problem by reading the xml file and getting the value of the desired attribute.
  56. Bayla 9/7/2005 8:21 AM
    Gravatar
    I see a few people asked about sharing one config between a few applications, and the answer seems to be to read the xml file as a regular xml file not as a config file. Was just wondering if someone had a simple snippet of code to do this reading of the config file format code.
    If you can post it, it would be appreciated.
    Thanks,
    Bayla N
  57. Bayla 9/7/2005 9:31 AM
    Gravatar
    Hi,
    I am posting the function I wrote to read the xml from a file with the same layout as the config file.
    Its vb.net code:

    Public Shared Function ReadConfigSetting(ByVal key As String) As String
    Try
    Dim doc As XmlDocument
    Dim node As XmlNode
    doc = loadConfigDocument()

    'retrieve appSettings node
    node = doc.SelectSingleNode("//appSettings")

    If node Is Nothing Then
    MsgBox("Could not find <appSettings> section in the app.config file", MsgBoxStyle.Exclamation, "Section Missing")
    Else
    'select the 'add' element that contains the key
    Dim elem As XmlElement = CType(node.SelectSingleNode(String.Format("//add[@key='{0}']", key)), XmlElement)

    ReadConfigSetting = elem.GetAttribute("value")

    End If
    Catch exc As Exception
    'add in error handling here
    End Try
    End Function

    Hope this helps someone...
    Bayla
  58. Tom Burk 9/20/2005 11:25 AM
    Gravatar
    Hi,

    I am using the code snip to read/write to a app.config file. the code posted for vb.net is never finding the key, here is the result below. What can you recommend?

    code snip:
    elem = node.SelectSingleNode(Format("//add[@key='{0}']", key))
    if elem is nothing = false then
    [always evaluates to TRUE]

    here is result:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <appSettings>
    <add key="Inbound_Nortel" value="C:\TEST_DIR\02560\archiveInOrder" />
    <add key="LastProcessed_Nortel" value="3/15/2005 12:00 AM" />
    <add key="LastProcessed_Nortel" value="9/20/2005 2:51 PM" />
    <add key="LastProcessed_Nortel" value="9/20/2005 2:52 PM" />
    <add key="LastProcessed_Nortel" value="9/20/2005 2:52 PM" />
    <add key="LastProcessed_Nortel" value="9/20/2005 2:52 PM" />
    <add key="LastProcessed_Nortel" value="9/20/2005 3:17 PM" />
    <add key="LastProcessed_Nortel" value="9/20/2005 3:17 PM" />
    </appSettings>
    </configuration>
  59. Kris 9/22/2005 8:27 AM
    Gravatar
    Can anyone help me out.
    I have a class library project, build and reference the .dll in Web application. Problem is, my client wants to pass the parameter to .dll using app.config from class library project it self. I am getting null value by using ConfigSettings.AppSettings["Key"].

    If you can post it, it would be appreciated.

    Thanks
    Kris
  60. Chris 9/26/2005 9:00 AM
    Gravatar
    To Tom Burk:

    The person who wrote the VB.Net code should have used String.Format and not just Format. Change all those and you should be fine.

    Also, its good .net programming practice to remove the On Error GoTo statements and use try-catch blocks instead.

    Chris
  61. Husein Murselov 10/7/2005 5:35 AM
    Gravatar
    Nice work, Ryan

    There's the C++.NET version of your code, slightly modified.

    Regards,
    Huse

    using namespace System;
    using namespace System::Xml;
    using namespace System::Configuration;
    using namespace System::Reflection;

    __gc public class ConfigSettings
    {
    private:
    ConfigSettings() {}

    static XmlDocument* loadConfigDocument()
    {
    XmlDocument* doc = NULL;
    try
    {
    doc = new XmlDocument();
    doc->Load(getConfigFilePath());
    return doc;
    }catch (System::IO::FileNotFoundException* e)
    {
    throw new Exception("No configuration file found.", e);
    }
    }

    public:

    static String* getConfigFilePath()
    {
    return AppDomain::CurrentDomain->SetupInformation->ConfigurationFile->ToString();
    //return AppDomain::CurrentDomain->GetData("APP_CONFIG_FILE")->ToString();
    //return String::Format(S"{0}{1}", Assembly::GetExecutingAssembly()->Location, new String(".config"));
    }

    static String* ReadSetting(String* key)
    {
    String* res = ConfigurationSettings::AppSettings->Item[key];
    if (res==NULL) res = new String("");
    return res;
    }

    static void WriteSetting(String* key, String* value)
    {
    // load config document for current assembly
    XmlDocument* doc = loadConfigDocument();

    // retrieve appSettings node
    XmlNode* node = doc->SelectSingleNode("//appSettings");

    if (node == NULL)
    throw new InvalidOperationException("appSettings section not found in config file.");

    try
    {
    // select the 'add' element that contains the key
    XmlElement* elem = static_cast<XmlElement*> (node->SelectSingleNode(String::Format("//add[@key='{0}']", key)));

    if (elem != NULL)
    {
    // add value for key
    elem->SetAttribute("value", value);
    }
    else
    {
    // key was not found so create the 'add' element
    // and set it's key/value attributes
    elem = doc->CreateElement("add");
    elem->SetAttribute("key", key);
    elem->SetAttribute("value", value);
    node->AppendChild(elem);
    }

    doc->Save(getConfigFilePath());

    }catch (...)
    {
    throw;
    }
    }

    static void RemoveSetting(String* key)
    {
    // load config document for current assembly
    XmlDocument* doc = loadConfigDocument();

    // retrieve appSettings node
    XmlNode* node = doc->SelectSingleNode("//appSettings");

    try
    {
    if (node == NULL)
    throw new InvalidOperationException("appSettings section not found in config file.");
    else
    {
    // remove 'add' element with coresponding key
    node->RemoveChild(node->SelectSingleNode(String::Format("//add[@key='{0}']", key)));
    doc->Save(getConfigFilePath());
    }
    }catch (NullReferenceException* e)
    {
    throw new Exception(String::Format("The key {0} does not exist.", key), e);
    }
    }
    };
  62. Al 10/13/2005 7:00 AM
    Gravatar
    Great Work!

    I take the point that modifying the web.config will have undesirable effects. Can someone tell me are there any undesirable effects if I modify my .NET Windows Service config file which will be residing on the server?

  63. Rick 10/13/2005 2:06 PM
    Gravatar
    I'm so confused with this stuff in C# 2.0. I'm new to C#/.NET (coming from a Java background). I used the vs.net 05 beta to make the properties file and I added one string property to it, but it looks nothing like the examples I see with

    <add key="somekey" value="someValue"/>

    Instead my generated app.config file looks like:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <configSections>
    <sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
    <section name="ScriptRunner.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" />
    </sectionGroup>
    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
    <section name="ScriptRunner.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    </sectionGroup>
    </configSections>
    <userSettings>
    <ScriptRunner.Properties.Settings />
    </userSettings>
    <applicationSettings>
    <ScriptRunner.Properties.Settings>
    <setting name="SCRIPT_FILE" serializeAs="String">
    <value>scripts.xml</value>
    </setting>
    </ScriptRunner.Properties.Settings>
    </applicationSettings>

    </configuration>

    How am I supposed to read out the value of "SCRIPT_FILE"... I tried...

    ConfigurationManager.AppSettings["SCRIPT_FILE"];

    But that is not returning anything (no errors just not returning scripts.xml

    Any help much appreciated.
  64. asuri 10/19/2005 8:38 AM
    Gravatar
    Any body has a answer to Rick's question. How in the world you access applicationSettings properties?

    I have tried ConfigurationManager woth no success.

    Thanks
  65. PalS 11/12/2005 8:02 AM
    Gravatar
    I dll-ized the class and used a csharp app to use the static methods and I used the following to get the config file name:
    AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

    It worked just fine. But when accessed the same methods of the dll from a C++ application, the file name it some up with is the CppApp.dll.config where CppApp is the C++ application executable name without the .exe extn.

    WHY???????
  66. pchak 11/15/2005 11:57 AM
    Gravatar
    Great piece of code! One question:
    In the "WriteSetting" method, there is a an "else section",
    else
    {
    // key was not found so create the 'add' element


    where the key is added as an element. Can you think of an elegant way to not allow this and raise an exception to log the issue, etc.?
    thanks!
  67. Mathieu Cupryk 12/10/2005 6:03 PM
    Gravatar
    I am not sure how to implement the double click with the following:

    Private Sub dataGrid1_MouseDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGrid1.MouseDown

    gridMouseDownTime = DateTime.Now
    Console.WriteLine("dataGrid1_MouseDown ")

    End Sub

    Private Sub dataGrid1_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGrid1.MouseUp
    Dim pt = New Point(e.X, e.Y)
    Dim hti As DataGrid.HitTestInfo = DataGrid1.HitTest(pt)
    If hti.Type = DataGrid.HitTestType.Cell Then
    DataGrid1.CurrentCell = New DataGridCell(hti.Row, hti.Column)
    DataGrid1.Select(hti.Row)
    End If
    End Sub

    Private Sub TextBoxDoubleClickHandler(ByVal sender As Object, ByVal e As EventArgs)

    MessageBox.Show("TrueDoubleClick")

    End Sub
    Private Sub TextBoxMouseDownHandler(ByVal sender As Object, ByVal e As MouseEventArgs)

    If (DateTime.Now < gridMouseDownTime.AddMilliseconds(SystemInformation.DoubleClickTime)) Then
    MessageBox.Show("GridDoubleClick")
    End If
    Console.WriteLine("TextBoxMouseDownHandler ")
    End Sub

    Sorry to hit this to you in the new year. I have been trying a while but dont seem to be getting anywhere. Any help would be great.

    Mathieu
  68. Dennis 1/6/2006 5:55 AM
    Gravatar
    For those asking how to use one configuration file with multiple apps:

    Use the 'file' attribute for the appSettings node:

    <appSettings file="common.config">
    </appSettings>

    You can put this apps config items in this node, then all apps config settings go in common.config in its appSettings node.
  69. Ryan Farley 1/6/2006 6:15 AM
    Gravatar
    Dennis,

    Awesome tip. Thanks!

    -Ryan
  70. Luke D 1/8/2006 7:11 AM
    Gravatar
    DON'T USE THIS CODE FOR ASP.NET 2.0

    The 2.0 framework has implemented an interface for editing/modifying config files on the fly.

    Using the System.Configuration namespace, there is an object called a Configuration, which provides an interface for interacting with you web.config files. And System.Web.Configuration gives you the WebConfigurationManager, which opens config files for you.

    As a super simple example, the following code adds an application settings variable to the root web.config file.

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

    config.AppSettings.Settings.Add("test", "testvalue");
    config.Save(ConfigurationSaveMode.Minimal);

    You can open any level web.config by passing the appropriate path to the "Open" call. You can even open remote web config files using the WebConfigurationManager.

    The real beauty of this method is that you can read and write from custom configuration sections just like you do from framework provided sections (custom configuration sections are implemented with ConfigurationSection, ConfigurationElement, and ConfigurationElementCollection, and are super powerful and simple once you get the hang of it... do a search for them to find lots of tutorials).

    Hope this helps people.
  71. Vaasu 1/9/2006 12:05 AM
    Gravatar
    Is it possible to place the app.config file in different directory? I want to place this config file within a directory.

    Any Idea?

    Thanks in Advance!!!
    Vaasu
  72. MadPiano 2/2/2006 5:01 AM
    Gravatar
    Thanks, Ryan! One quick search and your solution solved a big problem for a client of mine. Great work!
  73. Don 2/9/2006 10:35 AM
    Gravatar
    I have an app.config that looks like the following:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <appSettings>
    <add key="teamListUrl" value="http://www.test.com/teams/list.asp?name=blue&type=text" />
    </appSettings>
    </configuration>

    I get an error looking for a semi-colon.

    If I change the url to the following, it works great:
    http://www.test.com/teams/list.asp?name=blue&amp;type=text

    Is there a better way? Thanks.
  74. Goran 2/13/2006 10:32 AM
    Gravatar
    Hi Ryan!

    great stuff!! - I have only one problem ... I cannot read/remove a key...

    conf.ReadSetting("mykey") &
    conf.RemoveSetting("mykey") - doesn´t work...

    conf.WriteSetting("mykey", "mystring") works great!! but it adds me for every key a new line in my config file ... so if I like to change a key I have two entries with the same keys - so I thought to delete the old stuff before saving the new keys - and than your app. says [nykey] doesn´t exist....

    thanks
    Goran
  75. SpyKraft 8/11/2006 1:10 AM
    Gravatar
    JAG<If you are using this class in a dll and replacing Assembly.GetExecutingAssembly().Location + ".config";
    in the getConfigFilePath() method.

    Its a little better than
    AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString();
    to use:
    AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

    Both return identical strings. I just think the second one is easier to remember and there's less chamce for a typo.

    5/18/2005 7:18 PM
    >

    Hey thanks a lot JAG and Ryan, this helped me alot in retrieving back my web.config path !
  76. ziros 8/13/2006 4:49 AM
    Gravatar
    anyone encounter my problem? after i change the web.config filem when moving to another page the seession vars setting to null ?
  77. Ryan Farley 8/13/2006 10:17 AM
    Gravatar
    ziros,

    Yes, of course. If you are doing this in an ASP.NET application then writing to the config file is *not* a good idea.

    As I mentioned in the article "Every time you touch the web.config file the web app will recycle. Doing this often will throw performance out the window."

    This means that you'll loose session, etc. Not a good idea for web apps, unless the web app is some sort of one-time run installer or something.

    -Ryan
  78. Steve Flanders 8/14/2006 8:02 AM
    Gravatar
    Thanks for the assist everyone!

    As previously noted the app.config file is not reloaded automatically. To get around this, simple read the file manually:
    I apoligize if someone has already covered this...

    ' Modified:
    Public Shared Function ReadSetting(ByVal key As String, Optional ByVal DirectFileRead As Boolean = False) As String
    If DirectFileRead Then
    Return ConfigFileReadSetting(key)
    Else
    Return ConfigurationSettings.AppSettings(key)
    End If
    End Function

    ' New:
    Private Shared Function ConfigFileReadSetting(ByVal key As String) As String
    Dim doc As XmlDocument = loadConfigDocument()
    Dim node As XmlNode = doc.SelectSingleNode("//appSettings")
    Try
    Dim elem As XmlElement = CType(node.SelectSingleNode(String.Format("//add[@key='{0}']", key)), XmlElement)
    If Not IsNothing(elem) Then
    ' Key was found, change the value for that key.
    Return elem.GetAttribute("value")
    Else
    Return ""
    End If
    Catch ex As Exception
    Return ""
    End Try
    End Function
  79. ziros 8/15/2006 11:19 PM
    Gravatar
    Ryan thx for explanation
  80. Tarique 8/27/2006 11:40 PM
    Gravatar
    Great help Mate!! Thanks alot
  81. Andrew 10/13/2006 10:50 AM
    Gravatar
    If I understand correctly *.config files are loaded once per application session, therefore dynamic variables stored in these files are not very effective or efficient as the CLR will reload the app if changes are detected.

    2) <appsettings file="myFile.config" /> --- Are settings stored in myFile.config subject to the same limitations?

    3) Where should a web application's settings be stored? (Aside from the registry).

    TIA
  82. Luiz Estevo 12/13/2006 1:30 PM
    Gravatar
    Hi Ryan,

    Great Job!!!
    This code was exactly what I was looking for. It's a life saviour!! :)

    Thanks a lot,

    Luiz Estevo
  83. ureyes84 1/24/2007 6:40 AM
    Gravatar
    Hey guys, I`m writing an Installer class for a website, and I'm trying to write onto the web.config file from the "Commit" method and I have been getting the exception: "appSettings section not found in config file" in the middle of the installation.

    I added the next line:

    EventLog.WriteEntry("MyApp - web.config", doc .InnerXml);

    just after this:
    XmlDocument doc = loadConfigDocument();

    And I can see all the contents of the web.config file !!

    I copied and pasted the above code.

    Does any body have an idea why it`s not working?
  84. MsBugKiller 5/4/2007 6:10 AM
    Gravatar
    awesome Ryan. That's exactly what I need.
  85. FlatWhite 5/8/2007 5:33 AM
    Gravatar
    Just wondering, is there any other forum, discussion etc. started in 2004 and still getting replies in 2007?

    Good job.

    Question: How would you update a setting value other than delete and rewrite approach?
  86. Ryan Farley 5/8/2007 9:30 AM
    Gravatar
    Thanks FlatWhite :-p

    As far as for updating a value, the code above does that. The WriteSetting method will first attempt to locate the setting, if found it will simply update it. If not found it will create it in the XML and set it's value.

    -Ryan
  87. kavs 5/21/2007 2:27 AM
    Gravatar
    Its an amzing code as far i have went through !!!
  88. Vishal Nayyar 5/30/2007 5:07 AM
    Gravatar
    good Work Ryan,keep it up,it is helping me lot in making a smtp server
  89. Fresh Mexican Food Fan 6/15/2007 8:58 AM
    Gravatar
    Any plans to update this article for .Net 2.0 ?
  90. logicchild 8/3/2007 6:31 PM
    Gravatar
    Your article provides an excellent explantion of the types that can be in part of a source code ifle and become a file that can be deployed. As such, the logic reveals that assemblies can join to form a module. But any Win32 executable is hosted by a process. The process contains a collection of resources in order to execute the program and map it into memory, while letting the working thread execution stay on schedule. An application domain is isolated in a process, even though a process can have many of them. The core is that the CLR is a classic COM server, so every appdomain is configured, loaded, and unloaded separately while contained in the process. the .NET applications have runtime boundaries and will be kept separate. Keep managing those configuations, especially in Web.config's application's settings.
  91. Jako 8/10/2007 4:46 AM
    Gravatar
    Thanks Ryan, this really helped me a lot. To all noobs maoning about it not working: First add a referance to System.Configuration to your project before replacing ConfigurationSettings with ConfigurationManager. Hope that helps some of the youngbloods.
  92. Arno 9/30/2007 3:52 AM
    Gravatar
    Hi Ryan,

    a very good and professional code!

    Best regards

    Arno
  93. CLaudiu 10/4/2007 6:44 AM
    Gravatar
    hy,
    I modified a value for a key from a appSettings.config file but my web application is using the old one . This is happening until i reset the IIS. I modified the value manualy.

    Thanks for reading this!
    Claudiu.
  94. Malik 11/5/2007 5:23 AM
    Gravatar
    Thanks man, really helped my cause. Good job with the code.
  95. Gowri 11/20/2007 12:16 AM
    Gravatar
    HI i am trying to trigger an exe from a web application which resulting in 'configuration system failed to initialize' error. This happens exactly on accessing a key value from app.config in exe code. Please help me in resolving this issue.
  96. Lea 11/29/2007 3:21 AM
    Gravatar
    Hi Ryan,

    A very good and professional code! I wish that I found this link before because I spent 2 days to find that by myself :( . I'm newbie to C#.net with Java background. Now I have a new problem with this and I hope that you can help me.
    Here is my problem:
    I have a vb6 application that calls a webservice written in C#.net and this webservice calls an executable also written in C#.net. I'm not able in my executable to read information from the config file( which is applicationName.exe.config ) when I tested it from a vb6 application eventhough I am able to read it when I call it directly from IE (http://servername/webservicename/applicationName.exe).

    Note that my vb6 application can be installed on 2 tiers system (client and server) or on 2 in 1 tier system.
    This problem doesn't appear when I work on 1 tier system, I got only problems when the vb6 application is installed on 2 tiers systems.

    I tried 3 ways till now to set the config file inside the exe application:

    1- AppDomain.CurrentDomain.SetData(APP_CONFIG_FILE,"AppName.exe.config"); since this file exist in the same directory with the exe.
    2- AppDomain.CurrentDomain.SetData(APP_CONFIG_FILE,"C:/Inetpub/wwwroot/ServiceDirectory/ExeDirectory/AppName.exe.config"); .
    3- AppDomain.CurrentDomain.SetData(APP_CONFIG_FILE,Assembly.GetExecutingAssembly().Location + ".config"); .

    Actually, in #2, when I try to check how the application is reading the path, I got the path as http://servername/webservicename/applicationName.exe.config and not the full path.

    Do you have any idea why it is not working when I run it from the 2 tiers vb6 application and working when the vb6 application is installed only in the 2 in 1 system?

    Thanks in advance,
    Lea
  97. Bobby 12/3/2007 12:08 PM
    Gravatar
    Nice article. Just wondering, you can do the same thing (read/write) using System.Configuration.Configuration, isn't it?
  98. Khayralla 2/6/2008 6:23 PM
  99. Siddharth 3/19/2008 2:01 AM
    Gravatar
    hi

    i have gone through ur code.. and its really good.. but i am having a problem.. in application.config file we need to provide the path of the XML file but if i relocate the entire c# project to another directory..then i need to again specify the new XML path...So can u pls tell me how to solve this problem....

    regards
    Sid
  100. Novin 6/25/2008 1:51 AM
    Gravatar
    Great work RYAN
    It saved my effort!
    Thanks!
  101. Isuka 6/28/2008 10:31 AM
    Gravatar
    Ryan,

    Do you know how to update an app.config section which refers to an external xml file. I want to update the external xml file. Please let me know.

    Thank you
    Isuka
  102. Mark Montero 7/16/2008 4:02 AM
    Gravatar
    after updating the app.config file,
    you must invoke the refreshsection specifying the section to refresh
    so that next the you read the app.config, it will reflect the new values.

    System.Configuration.ConfigurationManager.RefreshSection("connectionStrings")
  103. mahmoud 8/17/2008 4:44 AM
    Gravatar
    Hi
    here is my case, I am using windows service with an application that contorl it, they are both located in the same solution (hmm, I don't know if it is good to put them the same in the same soltion, well this is not my question, but you may answer to give good programming practice). my problem is that the code assumes that the config file is located in the same pace as the exe; But in my case the config file is located with the MyWindowsService.exe, how I can write to this config file using the windows application, which is located in another folder as you surely know?

    please help me, becasue i need to write the setteing using the windows application and read these settings in the winodws service
  104. Aravind Kumar 8/28/2008 10:44 PM
    Gravatar
    Hi,

    Its a great stuff and direct point rather than unnecessary things.
  105. ASP Net 2.0 Migration 9/4/2008 12:16 AM
    Gravatar
    Great work Ryan
  106. Han Stehmann 9/12/2008 1:32 AM
    Gravatar
    Love it !
  107. kavitha 12/2/2008 4:15 AM
    Gravatar
    hi,

    i am working .net 2.0 windows application c#
    while running i change config file value it is updated in config files.the updated value is not taken for the first time it takes previous value.
    here is the code please solution for this.
    app.config files
    ----------------
    <add key="TaskServer" value="http://localhost:8080/axis2/services/Task" />
    <add key="DiscrepancyServer" value="http://localhost:8080/axis2/services/Discrepancy" />

    here is update app.config file
    -------------------------------
    // To Update in Exe Config
    string sFileLoc = System.Windows.Forms.Application.StartupPath + "\\As-one Desktop.exe.config";
    // string sFileLoc = @"C:\As-one\As-One Desktop\Resources\App.config";
    XmlDocument myXmlDocument = new XmlDocument();
    myXmlDocument.Load(sFileLoc);
    XmlNode xmlNdTask = myXmlDocument.SelectSingleNode("//appSettings/add[@key='TaskServer']");
    XmlNode xmlNdDiscrepancy = myXmlDocument.SelectSingleNode("//appSettings/add[@key='DiscrepancyServer']");
    XmlNode xmlNdContact = myXmlDocument.SelectSingleNode("//appSettings/add[@key='ContactServer']");
    XmlNode xmlNdResource = myXmlDocument.SelectSingleNode("//appSettings/add[@key='ResourceServer']");
    XmlNode xmlNdMailServer = myXmlDocument.SelectSingleNode("//appSettings/add[@key='MailServer']");
    XmlNode xmlNdWorkProduct = myXmlDocument.SelectSingleNode("//appSettings/add[@key='WorkProductServer']");
    string sTaskServer = "http://" + txtHostNew.Text + ":" + txtPortNew.Text + "/axis2/services/Task";
    string sDiscrepancyServer = "http://" + txtHostNew.Text + ":" + txtPortNew.Text + "/axis2/services/Discrepancy";
    string sContactServer = "http://" + txtHostNew.Text + ":" + txtPortNew.Text + "/axis2/services/Contact";
    string sResourceServer = "http://" + txtHostNew.Text + ":" + txtPortNew.Text + "/axis2/services/Resources";
    string sworkproduct = "http://" + txtHostNew.Text + ":" + txtPortNew.Text + "/axis2/services/WorkProduct";
    string sMailServer = txtMailServer.Text;
    xmlNdTask.Attributes["value"].InnerText = sTaskServer;
    xmlNdDiscrepancy.Attributes["value"].InnerText = sDiscrepancyServer;
    xmlNdContact.Attributes["value"].InnerText = sContactServer;
    xmlNdResource.Attributes["value"].InnerText = sResourceServer;
    xmlNdMailServer.Attributes["value"].InnerText = sMailServer;
    xmlNdWorkProduct.Attributes["value"].InnerText = sworkproduct;
    myXmlDocument.Save(sFileLoc);
  108. Aaron 12/22/2008 6:46 PM
    Gravatar
    hello,

    How do you select what file you want to use?

    Im using vb.net 2008 and I want to be able to read/delete/edit/add items to an XML file.

    I want to be able to use the XML file like below:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <appSettings>
    <add key="Test1" value="My value 1" />
    <add key="Test2" value="Another value 2" />
    </appSettings>
    </configuration>

    but I have no idea how to do it or know how to use the code above.

    Are you able to create and example and post it online somewhere?

    Hope you can help me out.

    Thanks.
  109. 1/20/2009 8:33 AM
    Gravatar
    Registrierung und Berechtigungen | hilpers
  110. 1/21/2009 8:20 AM
    Gravatar
    Scrivere nel web.config | hilpers
  111. 1/21/2009 10:53 PM
    Gravatar
    Reread of .config | keyongtech
  112. Vijay 2/5/2009 7:51 AM
    Gravatar
    Ryan,

    This helped me for my current project on time. Thanks. By the way, you look more like Michael Keaton (The one who acted in Batman movies). :)

    Thanks,
    Vijay
  113. Vivek 2/18/2009 10:19 PM
    Gravatar
    Hi All,

    I am working on windows application in 1,1 and able to update the app.exe.config file but not able to update the app.config file and when i restart the application it resets to the older value.

    Please revert.

    Thanks
    Vivek
  114. Abdul Mannan 4/3/2009 9:12 AM
    Gravatar
    Thanks every body, especialy Ryan Farley.

    I want to save and read user preferences, what sort of file should I use,
    Is use of a config file is a good idea?
    plz help me.
  115. dinesh 4/28/2009 6:35 AM
    Gravatar
    Hello ryan,

    Good work thank you. I wrote the key successfully in the myapp.exe.config like this below.

    <applicationSettings>
    <BSCW_UPLOAD_TOOL.Properties.Settings>
    <setting name="BSCW_UPLOAD_TOOL_cwe_shared_SharedWorkspaces" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    <setting name="BSCW_UPLOAD_TOOL_cwe_pro_WorkspaceSynchronization" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    </BSCW_UPLOAD_TOOL.Properties.Settings>
    <add key="rem.checked" value="true" /> //This is the line i added
    </applicationSettings>

    but when i try to remove the node only contain
    <BSCW_UPLOAD_TOOL.Properties.Settings>
    <setting name="BSCW_UPLOAD_TOOL_cwe_shared_SharedWorkspaces" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    <setting name="BSCW_UPLOAD_TOOL_cwe_pro_WorkspaceSynchronization" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    </BSCW_UPLOAD_TOOL.Properties.Settings>
    not with this line

    <add key="rem.checked" value="true" />

    Why is that ryan any idea ?..


  116. dinesh 4/28/2009 6:37 AM
    Gravatar
    Hello ryan,

    Good work thank you. I wrote the key successfully in the myapp.exe.config like this below.

    <applicationSettings>
    <BSCW_UPLOAD_TOOL.Properties.Settings>
    <setting name="BSCW_UPLOAD_TOOL_cwe_shared_SharedWorkspaces" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    <setting name="BSCW_UPLOAD_TOOL_cwe_pro_WorkspaceSynchronization" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    </BSCW_UPLOAD_TOOL.Properties.Settings>
    <add key="rem.checked" value="true" /> //This is the line i added
    </applicationSettings>

    but when i try to remove the node only contain
    <BSCW_UPLOAD_TOOL.Properties.Settings>
    <setting name="BSCW_UPLOAD_TOOL_cwe_shared_SharedWorkspaces" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    <setting name="BSCW_UPLOAD_TOOL_cwe_pro_WorkspaceSynchronization" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    </BSCW_UPLOAD_TOOL.Properties.Settings>
    not with this line

    <add key="rem.checked" value="true" />

    Why is that ryan any idea ?..

  117. dinesh 4/28/2009 11:24 AM
    Gravatar
    hello ryan,

    I solved the problem. But i have another problem after the add the key like this to my myapp.exe.config my application fail to run and display's the error "Configuration system failed to initialize".
    <applicationSettings>
    <BSCW_UPLOAD_TOOL.Properties.Settings>
    <setting name="BSCW_UPLOAD_TOOL_cwe_shared_SharedWorkspaces" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    <setting name="BSCW_UPLOAD_TOOL_cwe_pro_WorkspaceSynchronization" serializeAs="String">
    <value>http://www.cwe-projects.eu/bscw/bscw.cgi/</value>
    </setting>
    </BSCW_UPLOAD_TOOL.Properties.Settings>
    <add key="rem.checked" value="true" /> //This is the line i added
    </applicationSettings>

    Is there something wrong how i added the key?..

    Thank you.

    Dinesh.
  118. Janjua 6/8/2009 9:02 PM
    Gravatar
    Hey nice article,

    Can you help me in how to get a current system drive Or Program file path in Config file??

    Is there any tag?
    Urgent help

    plz
  119. Ratheesh KN 6/20/2009 8:49 AM
    Gravatar
    When i start windows XP A error Reads>could not locate the application configuration file>ventcfg >does this sisuation apply to this subject ? Can you please help on this as I am not much aware about system settings.
  120. G 6/25/2009 1:42 PM
    Gravatar
    Wow! Solved all my app.config problems in minutes! Works like a charm. Kudos!
  121. Christopher 1/17/2010 9:06 AM
    Gravatar
    Hi,

    I tried it on C# window form and it works perfectly.

    I converted it for windows mobile. I use the same code, import OpenNETCF.Configuration but im facing some problem. Each time I write to the file, it trims off a character from the XML file.

    For example,
    ============================================
    Before writing:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <appSettings>
    <add key="helloworld" value="10000" />
    </appSettings>
    </configuration>

    After writing:
    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <appSettings>
    <add key="helloworld" value="10000" />
    <add key="Test1" value="Thi
    ================================================

    Any reason why?
  122. Rameshkumar 2/3/2010 4:05 AM
    Gravatar
    Hi,

    This is good article.

    I am trying to update the appsetting key value. It has updated perfect using this class in VB.Net windows application. I have questions about this.
    1. I could not see the updated value in actual application configuration file.
    2. I could not read updated value immediate. If i close application then it will show

    Any reason ?

    Thanks

    Rameshkumar.T
  123. John 3/2/2010 1:22 PM
    Gravatar
    this is useless, as win7 and 2008 do not allow writing to program files. Why would MS put the darned config files in program files, and then tell us all "do not save any application data in program files"?????
  124. paranic 7/22/2010 7:43 AM
    Gravatar
    hey thats great!
    i will use that for my custom user config for an applicaiton of myne.
    i will store custom.user.config to customer's private folder for reading and writing.

    thanks for the tips
  125. M N Omer Khan 8/8/2010 7:43 AM
    Gravatar
    Every time I open windows 7 I see a message box stating that -ventcfg : "Could not locate application configuration file". What is this please help me to get rid off this problem
  126. 11/27/2012 2:04 PM
    Gravatar
    Writing to Your .NET Application&amp;#8217;s Config File
  127. 7/30/2013 12:12 PM
    Gravatar
    What is App.config in c#.net?How to use it? | Q Sites
  128. 11/18/2014 6:29 PM
    Gravatar
    Multiple .NET Configuration Files and Setup Project Problem | Zickler
  129. 12/5/2014 5:35 PM
    Gravatar
    Programatically adding sections to the configuration read from app.config | Yoshizawa Answers
  130. 12/6/2014 10:12 PM
    Gravatar
    app.config weirdness | Youd Answers
  131. 12/7/2014 12:34 PM
    Gravatar
    .NET configuration file &amp;#8211; Do I need to include it in installer? | Zarozinski Answers
  132. 12/12/2016 5:57 AM
    Gravatar
    How To Get Appsetting Values In Aspx File | 247
  133. 12/8/2017 12:56 AM
    Gravatar
    <br />Read Variable from Web.Config - ExceptionsHub
  134. 12/5/2019 3:23 AM
    Gravatar
    Writing to Your .NET Application&amp;#039;s Config File &amp;#8211; Bojensen Blogs
Comments have been closed on this topic.



 

News


Also see my CRM Developer blog

Connect:   @ryanfarley@mastodon.social

         

Sponsor

Sections