I want to update app. config file in windows form c# . here is a code for updating app. config
// updating
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings.Remove("name");
config.AppSettings.Settings.Add("name",txtName.Text);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
// show updating result on labels ( and this work fine )
string value = ConfigurationManager.AppSettings["name"];
lblName.Text = value;
this update work fine when I am running an application but when I restart application all config is reset to default
Instead of using the Configuration class, open the file as a regular Xml file and make your changes. Note that when you are doing this, when you save the file back, any Comments in your .config file will be removed by the Xml class. To prevent this, you must read ALL types of Xml nodes from the original configuration file and write them all back.
Related
I am needing to find away to write to another programs app.config file.
we have a 3rd party application that gets some values from an AppSettings section in its own config. but the only way we can get to change the value is when we call the application and once it runs it does a function which we don't want it to do if it doesn't have the correct values.
We need to encrypt one of the values so what we were think of was creating an application that would save the values in this 3rd party app.config.
saving the values and the encryption aren't a problem its doing it in another applications config file.
Is there a way to set which config file we use or a config path setting?
Regards
Aidan
Thank you for the help with this, I managed to get it done through this code.
string configLocation = string.Format("{0}\\APP.exe.config", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
ExeConfigurationFileMap map = new ExeConfigurationFileMap();
map.ExeConfigFilename = configLocation;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
txtEndpoint.Text = config.AppSettings.Settings["ENDPOINT"].Value;
This now allows me to write out the set config file values in the appsettings.
Cheers All.
Aidan
I would like to change values in my app.config file (or rather MyProgramName.config file) at runtime. This works fine using
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
//update values in config.AppSettings...
config.Save(ConfigurationSaveMode.Modified);
However the MyProgramName.config file is always stored in the program folder according to the documentation (https://msdn.microsoft.com/de-de/library/system.configuration.configurationuserlevel%28v=vs.110%29.aspx)
Application configuration files are in the same directory as the application and have the same name, but with a .config extension. For example, the configuration file for C:\System\Public.exe is C:\System\Public.exe.config.
Now lets assume I have some users who can not write to C:\Program Files(x86)\... (which is the default setting for non-admin users on win7). Is there a way to still use the app.config file properly or maybe place it in the %APPDATA% folder?
You can use the User settings capability of the application settings api for this. These settings are stored in %userprofile%\appdata\local or %userprofile%\Local Settings\Application Data (windows version dependent).
User settings has some limitations: it is, as it says, user specific not global for all users - but presumably if you are updating values at runtime then that's what you want, otherwise you need something like this.
You essentially just have to add a .settings file, which creates the applicationSettings and/or userSettings sections in your app.config (see MSDN: How To: Create a New Setting at Design Time), create your property and set it to User, not Application, and then do this at runtime:
Properties.Settings.Default.myColor = Color.AliceBlue;
Properties.Settings.Default.Save();
The .settings property will create a user settings entry in your app.config that looks like this:
<setting name="Setting1" serializeAs="String" >
<value>My Setting Value</value>
</setting>
You can use this to set the default value that a user session will get before any user-specific value has been saved.
Reference: MSDN: Using Application Settings and User Settings
Data, stored in app.config, are not intended for changing by regular user at run-time. Do not write a code, which re-writes app.config, except the case, when this code is located at some config application for admin. Use application settings instead.
I am having two projects one is basically a Windows service and second is class project in which I am doing my business processing. My App.config file is in Windows service project and in my Class project I am using below
ConfigurationManager.RefreshSection("appsettings");
string scheduledTime = ConfigurationManager.AppSettings["ScheduleTime"];
this setting is in my appsettings section of config file
I am using RefreshSection and also updating my app.config value in windows service project but its not getting updated at run time in my class project.
What is the catch in this ?
I'm having a little trouble myself with something similar, however I did come across something for AppSettings. Give this a shot:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
I think appsettings should be appSettings
If you want to get latest value use this code:
var appSettings = ConfigurationManager.OpenExeConfiguration(System.Reflection.Assembly.GetEntryAssembly().Location).AppSettings;
var mySetting = appSettings.Settings["keyOfSetting"].Value;
remember every time you need latest value, must use two line of code in same place!
Below is the code i am using to update or change the values in appsetting in app.config
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["userName"].Value = username;
config.AppSettings.Settings["pwd"].Value = pwd;
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");
i am using above code to change or update the settings in appsetting section at runtime and want the changes to persist so that when i run the application it should pick the new values from appsettings but here it doesn't happen so the changes made and saved at run time do not persist when i relaunch my application again it has the old default settings. Also i checked app.config in bin/debug but it too had the old values in appsettings. i refered various blogs and post here too as a reference but it got the same code as above but it did not persist the settings.have referred this post
I had the same problem while ago. I would have preferred to put this in a comment but I don't have that privilege. My answer might not be your case but I think is worth to be shared.
May I ask you where your bin folder is located? Windows 7 when you programmatically alter a file that isn't in a user accessible space creates a copy of that file in a Roaming space and there the file will stay. Every time you try to access the file (like your app.config) W7 transparently redirect your readings/writings to this file, so there's a chance that you are modifying the file in the roaming space, leaving the one you are lookin unaltered.
Are the changes you are making still there the successive time you start the application?
Disclaimer/Apology: I'm not an experienced user so if I am saying silly things let me know and I will remove this comment.
See below(from MSDN) and remember app.config is in your project. .exe.config is the actual file name.
Client applications use a global configuration that applies to all users, separate configurations that apply to individual users, and configurations that apply to roaming users. The userLevel parameter determines the location of the configuration file being opened by indicating whether it has no user level (the configuration file is in the same directory as the application) or has a per-user level (the configuration file is in an application settings path determined by the user level).
Specify which configuration to get by passing one of the following values for userLevel:
To get the Configuration object that applies to all users, set userLevel to None.
To get the local Configuration object that applies to the current user, set userLevel to PerUserRoamingAndLocal.
To get the roaming Configuration object that applies to the current user, set userLevel to PerUserRoaming.
NoteNote
To get the Configuration object for a resource, your code must have read permissions on all the configuration files from which it inherits settings. To update a configuration file, your code must additionally have write permissions for both the configuration file and the directory in which it exists.
i got my solution of above problem, my goal was to persist changes done at run time at application or user level. Initially i tried using App.config where i kept default settings for application in appsettings section of app.config, but later after research i got to refer i got to know appsetting does not persist the changes, instead you can use userSettings section where under YourApplication.Property.Settings you can give your userlevel settings and it worked for me. To do this you do not need to go to App.config to do it manually, rather you can do it from the property window of project.
Right Click on your project -> Select Settings Tab on the left-> Now on the right hand side you will see the Resource section , give the ResourceName, Type, Scope and its value and you are done. The same value can be access and change dynamically from Code as well.
Below are Code Excerpt for the same --
Accessing Settings Value
enter code here
userName = Properties.Settings.Default.UserName;
pwd = Properties.Settings.Default.PWD;
Saving New Settings Back
enter code here
Properties.Settings.Default.UserName = userName.ToString();
Properties.Settings.Default.PWD = newPWD..ToString();
Properties.Settings.Default.Save();
And when you will launch your application next time you will get the new changed settings as your default settings.
I hope that helps
Thanks Guys
VJ
I have a desktop WPF application which uses Entity Framework 4.1 Code First approach to manage data.
EF adds a connection string to the App.config file and I wan't to be able to change this connection string at runtime.
Scenario is like this:
When I deploy the application it has a default connection string in the App.config file. The user runs the application and since the connection string will probably be invalid for the user (because of server name, user id and password) I will display a server configuration window.
Here user will enter the valid information about his connection and press OK. I will then be able to change the App.config file and save the user's new valid information to the file.
Problems:
If I change it using ConfigurationManager, the changes will be temporary meaning that the file is not saved, changes are made in memory.
If I read the App.config file into a stream, make required changes in the memory, delete physical file and save the in memory stream as App.config again, Windows will not let me make changes to files under ProgramFiles folder.
What is would be the best approach here?
EDIT: Problem Again!
After I modify the App.config file with this method:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save(); // This line throws an exception
ConfigurationManager.RefreshSection("connectionStrings");
}
config.Save(); method call throws an error saying
"Access to "C:\Program Files (x86)\MyCompany\MyApp\MyApp.exe.config"
is denied."
I know that files under "Program files" are immutable, so how can I handle this?
I couldn't modify ConfigurationManager.ConnectionStrings["key"] object, because it is readonly.
So I decided to add a new connection string to my App.config file so it looks like this:
<connectionStrings>
<add name="SomeUniqueName" connectionString="Data Source=(local)\SQLExpress;Initial Catalog=MyDb;User Id=sa;Password=password; MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
and then changed my DbContext constructor to take newly added connection string like this:
public MyContext()
: base("name=SomeUniqueName")
{
}
Here, the value of name attribute at connection string and constructor must match.
Then to change this newly added connection string at runtime I used a method like this:
private void ApplyChangesToConnectionString()
{
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString = GetChangesAppliedConnectionString(connectionStringsSection.ConnectionStrings["SomeUniqueName"].ConnectionString);
config.Save();
ConfigurationManager.RefreshSection("connectionStrings");
}
App.config is not the proper place to do this since it's a global configuration used by the application.
I recommend you to save the settings per user. See this related question : c# - approach for saving user settings in a WPF application?
App.config is the correct approach in my opinion, however I wouldn't rely on writing the file physically yourself. Instead, allow the framework to do the heavy lifting for you.
Check out the sample here.
EDIT: Glad Sandeep's comment above has helped you. Feel free to check out that link too if you want a bit more information!