Updating .config file with data from the user - c#

I am trying to save some settings to the appSettings section of my configuration file so I may use the data to carry out the processes of the program. On the click of a button I want the data coming from the user to be saved in the config file. The code I am using is:
private void button1_Click(object sender, EventArgs e)
{
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["key1"].Value = "value1";
config.AppSettings.Settings["key2"].Value = "value2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
}
Before the code is executed my app.config file looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<appSettings>
<add key="roshane" value=""/>
<add key="email" value=""/>
<add key="super" value=""/>
<add key="phone" value=""/>
</appSettings>
<connectionStrings>
<add name="AutoReportEmailerConnectionString"
connectionString="Data Source=roshane\sqlexpress;Initial Catalog=ICR_v5.0;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>
After the code is execute the programName.exe.config file is the same as the app.config. Is there something I am missing why the values are not being added to the programName.exe.config file?

config.Save(ConfigurationSaveMode.Modified) works only when you modify an exisint key in other words a key that was in the web config before if you need to actually add key values to the web config just call config.Save() with no parameters

If you want to add new Key to config file, need to add it first in Settings collection:
config.AppSettings.Settings.Add("Key", "Value");
Then call Save method.

Related

Can't read connection string from web.config

I have the following in my web.config located at the root of my project:
<configuration>
<connectionStrings>
<clear />
<add name="Default" providerName="System.Data.SqlClient" connectionString="Server=tcp:whoops;Encrypt=True;TrustServerCertificate=False;Connection Timeout=3000;" />
</connectionStrings>
<appSettings>
<add key="ConnectionString" value="test"/>
</appSettings>
....
I read from Startup.cs (this is an asp.net core web app):
string connection = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
However when I break on this, ConfigurationManager.ConnectionStrings and ConfigurationManager.AppSettings are empty (well, the first has some default connection string that is not the one in web.config).
What's going on here?
You will have to migrate the config to the new file appsettings.json
https://learn.microsoft.com/en-us/aspnet/core/migration/configuration?view=aspnetcore-2.1
Not saying this is how you should do it, but you can do the following...
In ASP.Net Core 2.2, you should be able to add an XML configuration to IConfigurationBuilder using
configBuilder.AddXmlFile("app.config");
Contents is pretty much the same as above...
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings configSource="connectionStrings.config" />
<appSettings>
<add key="Test" value="TestValue" />
</appSettings>
</configuration>
You should then be able to access AppSettings/ConnectionStrings using...
ConfigurationManager.ConnectionStrings
ConfigurationManager.AppSettings.AllKeys
{string[1]}
[0]: "Test"
ConfigurationManager.AppSettings.Get("Test")
"TestValue"

How do I overwrite the default settings value in the settings designer for my Connection String

I need to use a different connection string than the one in the default settings value in the settings designer in order to run on my staging PC.
I have in settings.designer.cs:
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=MyServer\\MyDB;Initial Catalog=MyDB;Integrated Security=True;Pers" +
"ist Security Info=True")]
public string MyConnectionString {
get {
return ((string)(this["MyConnectionString"]));
}
}
My app.config is this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<clear />
<add name="MyConnectionString " connectionString=Data Source=MyServer2\\MyDB;Initial Catalog=MyDB;;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
I want the application to use the settings in app.config but it persists in using the settings in the settings designer file.
I have tried various permutations of the following as well:
<add name="AppName.Properties.Settings.Default.MyConnectionString" connectionString=Data Source=MyServer2\\MyDB;Initial Catalog=MyDB;;Trusted_Connection=True"
providerName="System.Data.SqlClient" />
such as:
AppName.Properties.Settings.GlobalReference.Default.MyConnectionString
and:
ApplicationSettings.AppName.Properties.Settings.GlobalReference.Default.MyConnectionString
Any thoughts or ideas would be greatly appreciated.
In order for this to work, you have to have System.Configuration in your references.
you need to access the configuration Manager
System.Configuration.ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
change your connection string name to something more simple or you'll have to use all of that
System.Configuration.ConfigurationManager.ConnectionStrings["AppName.Properties.Settings.Default.MyConnectionString"].ConnectionString;
if you want to use system properties you should add the system.reflection reference

Updating a config file adds additional config sections

My goal is to programatically update a .config file belonging to another application.
I start off with a simple config file that looks like this...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test1" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
I then run my code to update the connection string named Test1 and rename it to Test2...
var configMap = new ExeConfigurationFileMap() { ExeConfigFilename = #"test\app.config" };
var externalConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
externalConfiguration.ConnectionStrings.ConnectionStrings[1].Name = "Test2";
externalConfiguration.Save(ConfigurationSaveMode.Minimal, true);
This saves the configuration file, but now looking at the file you will see some other data has been added to it...
ConfigurationSaveMode.Minimal
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Test2" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<trust level="Full" />
<webControls clientScriptsLocation="/aspnet_client/{0}/{1}/" />
</system.web>
</configuration>
ConfigurationSaveMode.Modified
Using the Modified setting I get even more "stuff"...
<configuration>
<appSettings />
<configProtectedData />
<system.diagnostics />
<system.windows.forms />
<uri />
<connectionStrings>
<add name="Test2" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.net>
<authenticationModules />
<connectionManagement />
<defaultProxy />
...snip...
What is this data and where has it come from? More importantly how can I stop it from being written into my file?
Try changing the ConfigurationSaveMode from
ConfigurationSaveMode.Minimal
to
ConfigurationSaveMode.Modified
Modified only saves the properties that you have changed.
From MSDN:
Full
Causes all properties to be written to the configuration file. This is useful mostly for creating information configuration files or moving configuration values from one machine to another.
Minimal
Causes only properties that differ from inherited values to be written to the configuration file.
Modified
Causes only modified properties to be written to the configuration file, even when the value is the same as the inherited value.
The way I have solved this was to set the Machine Configuration File to be the same as my EXE Configuration file, this way the .net Configuration object does not see that there is any difference between Machine and EXE when it is saving.
For example:
var fm = new ExeConfigurationFileMap();
fm.MachineConfigFilename = fm.ExeConfigFilename = #"C:\dude.config";
var c = ConfigurationManager.OpenMappedExeConfiguration(fm, ConfigurationUserLevel.None);
// Do Stuff
c.Save(ConfigurationSaveMode.Minimal, true);
This way you should not get the section in your config file upon save.

Getting configuration values rom XML file located in the same project

I am making a little program to copy pictures form one location to another. The information for the pictures are stored in a database so I need connections string and also I create a txt file with the final output from the operation and I want to store these two values in a App.Config.xml file.
The structure of my project is very simple :
And the XML files itself is :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
<createResultFile>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</createResultFile>
</configuration>
I want to use the connectionString and <createResultFile> value in my PictureTransferTool.cs. This is my first time working with XML file and C# (.NET in general) so I want what is the way to retrieve those config values?
You config file must be like below...
Config File :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="ResultFile" value="C:\Users\dv\Desktop\Leron\PictureStatus.txt"/>
</appSettings>
<connectionStrings>
<add name="MyDB" connectionString="Data Source=.\\DVSQLEXPRESS08;Initial Catalog=**;Persist Security Info=True;User ID=**;Password=**;MultipleActiveResultSets=True" />
</connectionStrings>
</configuration>
C# :
You can read Connection String like below
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString;
Console.WriteLine(connectionString);
You can read User Defined Settings like Below
var Resultfile = System.Configuration.ConfigurationManager.AppSettings["ResultFile"];
Console.WriteLine(Resultfile);
The Way I normally do user-defined parameters in my app.config is i put them in the appSettings tab.
<appSettings>
<add key="myStr" value="String Value" />
and then you can access it with
string myStr = System.Configuration.ConfigurationSettings.AppSettings["myStr"];
It works for me.
Linq;
using System.Xml.XPath;
...
var doc = XDocument.Load("test.xml");// You should put the way to your XML
var name = doc.XPathSelectElements("/configuration/connectionStrings/add").Value;
var name = doc.XPathSelectElements("/configuration/createResultFile/add").Value;

c# Application Configuration File: AppSettings Reads Empty?

This is my first time using an XML config file. In the solution explorer I right click, add, new item, application config. file.
I then edited the file to read...
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key1" value="1000" />
</appSettings>
</configuration>
...and tried to access it with...
Int32.Parse(ConfigurationManager.AppSettings.Get("Key1"));
...but it says that the parameter is null. I looked at just ConfigurationManager.AppSettings and it's AllKeys property has dimension 0.
What am I doing wrong?
Thanks!
Right-click on your project, choose Properties>Settings tab and edit your settings there because the config file is not the only place these values are stored at.
In your code use Settings.Default.MySetting to access the settings.
You'll need to add using MyProjectName.Properties; to your using statements in order to access the settings this way or you'll have to fully qualify it as MyProjectName.Properties.Settings.Default.MySetting...
I know this is super old but I just encountered this opening an old project. A reference to System.Configuration was missing.
To ensure get information from App.config using ConfigurationManager.AppSettings["<Key name>"]; be sure to set your values inside <appSettings> section.
Example:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key ="IntervalSeconds" value ="60000"/>
<add key ="OutputPathLog" value ="\\myserver\hackingtrack\Projects\Log\"/>
<!--Jorgesys si Elenasys sunt puisori-->
<add key="InputFeeds1" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds2" value="https://cld.blahbla.com//portadaKick.json" />
<add key="InputFeeds3" value="https://cld.blahbla.com//portadaKick.json" />
</appSettings>
</configuration>
Retrieving values:
string intervalSeconds = ConfigurationManager.AppSettings["IntervalSeconds"];
string inputFeeds1 = ConfigurationManager.AppSettings["InputFeeds1"]; ;
string inputFeeds2 = ConfigurationManager.AppSettings["InputFeeds2"];
string inputFeeds3 = ConfigurationManager.AppSettings["InputFeeds3"];

Categories