Andrzej Gis
Andrzej Gis

Reputation: 14316

Modify settings in app.config

I created a settings file.

There is a field UseXmlPatternForTestServer which i a bool. I set the scope to appplication and value to True. I can see it added some content to the .config file.

After compilation a modified the .config file in build directory:

<configuration>
    <applicationSettings>
        ...
        <Logic.Properties.Settings>
            <setting name="UseXmlPatternForTestServer" serializeAs="String">
                <value>False</value> // **modified to false**
            </setting>
        </Logic.Properties.Settings>
    </applicationSettings>
</configuration>

Even though the value is set to False, the line below returns True. Why? And how can I get the current value from the config file?

Properties.Settings.Default.UseXmlPatternForTestServer // returns true

edit

All the settings above are in a class library project referenced by my app. Maybe that's the problem?

Upvotes: 1

Views: 237

Answers (2)

Fabian Bigler
Fabian Bigler

Reputation: 10915

I encountered the same problem and because the scope 'user' didn't work for me either, I ended up creating my own XML config which I can serialize / deserialize and manage how I want it to be. That's also nice because you can store whatever you want in your config file (for example a list of objects).


Basically your model could look something like this:

public class Config
{
     public string UseXmlPatternForTestServer {get;set;}
     //your properties to store

}

Serializer class to load / save your config:

public static class XmlConfigSerializer
    {

        public static Config DeSerialize()
        {
                try 
                {           
                    if (!File.Exists("config.xml")) { return null; }

                    XmlSerializer serializer = new XmlSerializer(typeof(Config));
                    using (var fs = new FileStream("config.xml", FileMode.Open))
                    {
                        return (Config) serializer.Deserialize(fs);
                    }                   
                }
                catch (Exception ex)
                {
                    //log error
                    return null;
                }
        }

        public static void Serialize(Config config)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Config));
            using (var fs = new FileStream("config.xml", FileMode.Create))
            {
                serializer.Serialize(fs, config);
            }
        }
    }

Upvotes: 1

Software Engineer
Software Engineer

Reputation: 3956

Try using settings directly without class library project or change the scope of UseXmlPatternForTestServer to User instead of Application.

See User Settings in C#

Upvotes: 1

Related Questions