c# save settings - c#

Im building a small project that uses some settings features. I could change the DB Path and some other textfields.
Whats the best way in c# to save these settings? Is there some built in config or ini file that can be changed under runtime? Because if I change the DB Path i need it to do this without restarting the program. I know i ofc can build a simple textdoc and read from but I whant to use some standard c# way.
Thx for anyfeedback.
/Marthin

If you have a look in the project property pages you can add a settings file.
To use the settings in code you would do something like:
Properties.Settings.Default.SettingName
Do bare in mind though that these settings are local and would need to be specified on each machine
Here is a link to the settings class on MSDN
http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx

if you create a new c# windows form application you have by default the properties, try to expand the node in solution explorer, you will find the settings file where you could add your values, at runtime you could retrieve them and change them, after changing them you save them in this way:
Properties.Settings.Default.Save();

Related

Load a different MyExeName.config XML (Project Settings file) to the default one?

I see this question asked many times about the ASP.NET style of application settings where the loading is done and then the code contains calls to ConfigurationManager.AppSettings["MySettingHere"] ..
..but my WinForms app doesnt use this method. Instead it uses the Project Settings route (i.e. I call Properties.Settings.Default.MySettingName to get my value, and I edit my settings by getting properties on the project and choosing the Settings tab)
App.config as a file is present in the root of the project/solution, but there is also Settings.settings and Settings.Designer.cs and I think these are the ones used and transformed into compiled code that gets the data
Essentially Visual Studio provides a type safe wrapper around the settings load/save/value getting process, and what I'd like to do is supply a path of the settings file to load rather than have it stuck at taking the default MyExeName.config file from the application directory
I assume you want to load custom configuration file from desired location rather than loading the default config, then try this,
NOTE : You can't have more than one App.config in a project.The app will use the config file named YourExcecutable.exe.config which is by
default the file App.config. But you can have multipe configuration
files and load then as you need using code. But you can't keep all of
them loaded at the same time. you can only switch between the files as
you need.
System.Configuration.ConfigurationFileMap fileMap = new ConfigurationFileMap("path to new file");
System.Configuration.Configuration configuration = System.Configuration.ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
OR
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #"Config file path");
The only solution I have found so far is rather a poor man's solve..
When we use the Settings tab inside a project's properties, the solution will gain a Settings.Settings, Settings.Designer.cs under the project's Properties node and possibly also an app.config in the root of the project. Edits to these files directly seem to be copied/updated /synchronised by VS itself. It also maintains some code in the background to ensure data-typed access to these settings. Likely it's based on Configmanager.AppSetings["propertyName"] but because VS is used to set up the property, and you tell it it's an int (or whatever) then VS can write wrapper code that exposes a namespace/class/member chain of ProjectNamespace.Properties.Settings.Default.PROPERTYNAME
Seemingly this code relies on the settingsfile being called THE_EXE_NAME.exe.config and being stored alongside the EXE itself..
..so I just take the the settings file that I want to use, copy it over the top of the one stored on disk, and call ProjectNamespace.Properties.Settings.Default.Reload() which does reload the values I want to use out of the new file. I can think of countless reasons why this isn't ideal but it's all I've been able to come up with so far

How to get an Application Settings shared to all users that could be changed at run time

I need some setting of an application that will be shared among all users of the computer, but could also be changed at at run time. That seam simple, but according to the Application Settings MSDN article, it's either one or the other.
There are two types of application settings, based on scope:
Application-scoped settings can be used for information such as a URL for a Web service or a database connection string. These values are associated with the application. Therefore, users cannot change them at run time.
User-scoped settings can be used for information such as persisting the last position of a form or a font preference. Users can change these values at run time.
I could write code to edit the app.config XML file, but since it's located in the program directory, it's protected under windows 7. So this is not possible without elevating the program or playing with NTFS rights.
So I need the configuration file to be written in a common folder like System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData).
But this is a fairly common requirement!
So, I'm wondering if there a simple way of achieving this without reinventing the wheel, or if I have to write my own Setting Manager.
After reading the answers here and playing with the ConfigurationManager.Open methods I ended up with the following:
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MyApp", "MyApp.config");
Configuration MyAppConfig = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = path }, ConfigurationUserLevel.None);
The nice part is the file doesn't have to exist, and if you call Save() on it, it will create the folder and the file for you. AppSettings["key"] didn't work though so I had to use
MyAppConfig.AppSettings.Settings["key"].Value
to read and write an existing value and
MyAppConfig.AppSettings.Settings.Add("key", value)
to add a new value.
I have had a similar problem and ended up writing my own settings class. It was very basic. I created a Settings class with the properties I needed, and a SettingsManager with Save() and Load() methods that simply serialized/deserialized the object via XmlSerializer into/from a file.
Yes, it is your own code, but it is very simple code, takes less time than trying to figure out whether there is a component providing what you need and how to customize it.
The Application Settings infrastructure does not support this - only non-editable application data and user-scoped data are supported. You can easily read and write your own XML into the CommonApplicationData folders, however, instead of using the application data.

how to store settings for deployable c# application?

I want to store settings for my C# application, such that default setttings can be easily shipped with my binaries and the end-user can change them using a simple text editor(or in some other simple way).
I seem to face several alternatives : a .config file, .settings file or a .resx file. What are the pros and cons of these?
Edit1: End-users are computer professionals mainly, so editing these files should not be much of a problem.
Edit2: The settings are something like connection strings, and some other parameters (mostly one-time stuff). Building some kind of GUI/API for changing them is not really an option. Also my application will not edit any of these values, so persistence through code is not required.
Yes, Project + Properties, Settings tab was designed to do this. Add your settings here, change the Scope to Application. That generates a app.exe.config file in your build direcctory, deploy it along with your EXE. Use Properties.Settings.Default.SettingName in your code to obtain the setting value. Your user will normally need admin privileges to edit the .exe.config file on the target machine to change the setting value.
The small print: settings do not work well for DLL assemblies, you have to merge the .config files by hand. When using the debugger, settings are retrieved from the app.vshost.exe.config file.
The .settings file is a helper file used by the IDE, ignore it. .Resx files store resources, they get compiled and embedded in a binary form in an assembly. They are not editable by the user.
I think you can have two ways of doing this.
For regular users, you can make a custom GUI that will make it simple for them to use.
For advanced users, they can edit the configurations using a text editor if it's stored in a text file (ini file, config file, etc..) or you can make an API.
The .settings file is typically used for user-specific preferences and configuration information (whereas the .config file is used for global settings for the application or anything that modifies the .Net runtime. Simply putting parameters in a .config file can alter the behavior of your application even without you writing a single line of code for it).
Check out the Settings article on MSDN for more: http://msdn.microsoft.com/en-us/library/aa730869(VS.80).aspx
Since the file will be modified by the users, I think using app.config is not a good idea. What if they break the file structure? Or set an invalid value? Probably your application will crash directly.
One of the solutions would be to use a custom XML file. You will then validate it when your application starts. XSD will probably be the more elegant way to do it, but you can also parse it directly and validate it in code. If the file is invalid, instead of crashing, you will try to solve the problem, and if impossible, display a pretty error to the user, explaining that there is an error in XML at line n, position n, which is [error description here].
If the end user is really going to be editing them, I'm not sure I would want them editing my app.config file.
You have another couple alternatives that you haven't included. You could use an old-school .INI file that is simpler for an end user to understand. You could also use the registry. I would recommend the INI file, unless your users are very savvy, in which case use the .config file.
The answer depends on the deployment method. For instance, if you are using ClickOnce and offer updates, you might encouter problems using Application Settings.
I believe the best way to go is to create a GUI, something that is most certainly suitable for novice users. Given that you already excluded that option, use John's suggestion (ini files).

How do I create editable configuration settings in a C# WinForms application?

I have configuration values saved in an app.config. I want to create a WinForms application which shows all the AppSettings values in a form. The user should be able to change the settings values and save them back to the app.config.
As long as your values are in the appConfig section of the app.config file, you can simply use System.Configuration.ConfigurationManager.
ConfigurationManager.AppSettings - MSDN
Here's an old blog post explaining EXACTLY how to do what you're looking for:
Read/Write App.config
If you store the settings using the Settings.settings file in the Properties folder you can just do:
Properties.Settings s = new Properties.Settings();
And then all the settings will be properties of s (you can define them as a specific type even) and if they're set as user settings you can change them.
Just call Reload or Save on the instance of Settings to read/store from/to disk.
I was successful with using the method Justin Niessner suggested. One caveat to watch out for: When you are testing this in visual studio, the app.config itself won't be edited if you are debugging the application. The config file that is modified is the ProjectName.vshost.exe.Config
Have a look at System.ConfigurationManager. There's a huge example on the MSDN page showing almost all the necessary functionality to configure, alter, save, etc, all in the language of your choice.
The ConfigurationManager class
includes members that enable you to
perform the following tasks:
Read a section from a configuration file.
Read and write configuration files as a whole
Support configuration tasks.

How do you embed app.config in C# projects?

When you compile a C# project, the app settings from app.config are saved along with the exe file. For example, if the program name is "solve_np.exe", there will be a "solve_np.exe.config" next to it, making it look less neat than I want it to. How can you embed it into the .exe?
I tried to set Build Action to Embed Resource, but that did not do the trick.
Aha. I guess you're falling foul of Visual Studio automatically placing stuff in configuration that you DONT want configured by the end user.
In this case use resources. Simply add a new file of type .resx. With this you'll be able to add things like strings and images to the resource file. After you build this it should provide static access to the resources (it typically generates a code file from the resources for you so you don't have to access ResourceManager yourself).
E.G. If I made resources.resx with a string called MyConfigValue after a build I should be able to access this like:
textBox.Text = Resources.MyConfigValue;
If you want values that are kinda variable but shouldn't be configurable then this is the right place to put them.
HTH.
It isn't unprofessional to have an app.config file shipped alongside your exe. I think the word you may be looking for is untidy. I personally don't find this is the case myself however everyone is different! Perhaps you could simply make the app.config file hidden by default?
Or another alternative is to create your own config file which you could save to the App Data folder or even storing the settings in the registry instead.
Here's another factor to consider. Seasoned .Net developers are accustomed to the standard application design, which incorporates using config files in both web apps and desktop apps. If you depart from that practice, you will make it more difficult for any developers who follow you to understand what you have done. Even sa's on the web server may be confused by the absence of a config file.
Since pretty much everybody does it this way, your code does not look "untidy" to others. On the contrary, it would be befuddling not to see a config file where one is expected.
Typically the theory of a configuration file, is that it stores settings you may want to change once you've deployed the application (for something like user preferences). To do this, you need to be storing somewhere external to your application. If you use the default setup, you get "[Your].exe.config". There are many other options you could look at, but nearly every one of them ends up with a file written somewhere, if you providing a mechanism that saves settings of some kind.
I agree with serhio darasd and Quibblesome but you can just delete "solve_np.exe.config" and it'll just use default configs.
After considering what was written in these comments and other searching, I decided that the best way to handle my issue of wanting my Entity Framework connection string to be embedded into my executable instead of needing the MyApplication.exe.config file with my deployed solution was to created a derived class like such:
Public Class MyEFDataContainerLocal
Inherits MyEFDataContainer
Public Sub New()
MyBase.New(My.Settings.MyEFContainerConnectionString)
End Sub
End Class
I just created an Application Setting of type Connection String that contained the same string as what is found in the App.Config file. I just had to replace the &quote;'s with actual quotes.
Then whenever I wanted to use the MyEFDataContainer as in Dim db As New MyEFDataContainer I would just use Dim db As New MyEFDataContainerLocal instead.

Categories

Resources