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

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;
}
}
}

Leave a Reply

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