0 Comments

If you set your settings to the "Application" scope the settings will be read-only.

If you want to change these settings at runtime, you can use the following code from my unit test project:

 

First create a Settings class in your unit test project:

Right click on the unit test project and choose "Properties".

Click on "Settings":

Click on "This project does not contain a default settings file. Click here to create one."

 

image

 

At two test settings: "MyStringSetting" and "MyInSetting"":

 

image

 

image

 

The App.config will be changed like:

image

 

Now to show the code that changes the settings at runtime:

 

namespace UnitTestProject2
{
    using System;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using UnitTestProject2.Properties;

    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var settings = new Settings();
            
            Assert.AreEqual(settings.MyStringSetting, "This is some random text.");
            settings.ChangeSetting("MyStringSetting", "This is some other text.");
            Assert.AreEqual(settings.MyStringSetting, "This is some other text.");

            Assert.AreEqual(settings.MyIntSetting, 999);
            settings.ChangeSetting("MyIntSetting", 100);
            Assert.AreEqual(settings.MyIntSetting, 100);
        }
    }
    
}

namespace UnitTestProject2.Properties
{
    internal sealed partial class Settings
    {
        public void ChangeSetting<T>(string key, T value)
        {
            this[key] = value;
        }
    }
}

One Reply to “How to change Application scope Settings (that are read-only) at runtime in C#”

  1. How do you save changed settings? I tried
    settings.Save();
    but it doesn’t work.
    Thank you in advance for your reply.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts