Solved

C# - How to create, read from and write to a custom configuration file?

Posted on 2011-03-24
6
1,419 Views
Last Modified: 2012-05-11
I have a C# console app that I have to modify.
The app uses a config file to save to and read from some values that could be used for future runs.  It does not use properties file for that because with the properties file you still can write to but that properties file would be different for each user, and this should be user independent.
That;s why the config file is used.
Currently, the app has an app.config file that resides in the main directory where all the source code is located, and <app_name>.config file that is located in the executable file's directory (\bin\Debug in this case).  The values stored by the application in the <app_name>.config file that is located in the executable file's directory.
But every time the application is recompiled, the <app_name>.config file is being overwritten by the app.config file located in source directory, and the custom values are reset to the values stored in the app.config file.
Questions: 1) is it possible to change valued in the app.config file as well as in the <app_name>.config file (by the application) so that the new values are not reset during compilation.
2) If not, what are other options?  My idea is to use a custom config file that would be could be used to write to and read from custom data just as the <app_name>.config file is.
But how and where to create, read from and write to a custom configuration file?
Code samples would be much appreciated.

The current code to read from and to write to looks like this:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
string storedValue = config.AppSettings.Settings["Param1"].Value
string newValue = "param1_newValue";
config.AppSettings.Settings["Param1"].Value = newValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

Thank you!
0
Comment
Question by:pavelmed
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 19

Assisted Solution

by:Raheman M. Abdul
Raheman M. Abdul earned 150 total points
ID: 35207859
0
 

Author Comment

by:pavelmed
ID: 35208020
This example is for WebConfiguration Manager, web.config file and Virtual directories.
I have a console application with no web access.
Can the example still be used for the ConfigurationManager?
0
 
LVL 10

Accepted Solution

by:
wls3 earned 200 total points
ID: 35208214
Yes, can do a lot of this with console.

http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx

Also, I am bit of a Powershell nut, so, bear that in mind.  However, have you looked at attempting to resolve this the Powershell way?  Here is a very generic effort using the [XML] type to load the web.config and manipulate a setting:

http://get-powershell.com/post/2008/07/29/Editing-WebConfig-Files-with-PowerShell.aspx
0
[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

 
LVL 2

Assisted Solution

by:ericpeckham
ericpeckham earned 150 total points
ID: 35219428
I've found it easiest just to create an XML file from your application, to store system-wide settings that can be changed at runtime.  That way you can put it where you want, and you have full control over it.  Messing around with custom configuration files has always been a pain and a disappointment for me.
0
 

Author Comment

by:pavelmed
ID: 35342956
Sorry I had to delay my final comments due to unrelated issues I was fully occupied with.

I ended up with a compromised solution - I kept saving the changes in the <app_name>.config file in the executable file directory, but after that I also saved the new values in the app.config file in the source code directory so that if a project is recompiled, the <app_name>.config and app.config files would have the same values.

// keeping the newly saved values in the <app_name>.config file
config.AppSettings.Settings["Param1"].Value = newValue;
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

// saving the new values also in the app.config file in the source code directory (if the directory and file exists)
// In my project, the exe file directory is two levels below the source code directory.
// and of course, I surrounded the code in try/catch block (now shown below)

string appExePath = Path.GetDirectoryName(Application.ExecutablePath);
int lastBSPos = appExePath.LastIndexOf("\\");
string appConfigPathDir = appExePath.Substring(0, lastBSPos);
lastBSPos = appConfigPathDir.LastIndexOf("\\");
appConfigPathDir = appConfigPathDir.Substring(0, lastBSPos + 1);
if (Directory.Exists(appConfigPathDir))
{
    config.SaveAs(appConfigPathDir + "app.config", ConfigurationSaveMode.Full);
    AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", appConfigPathDir + "app.config");
}

I am going to split the points between participants of this call.
Thank you!
0
 

Author Closing Comment

by:pavelmed
ID: 35343016
I ended up with a compromised solution
0

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question