I have a project that reads in a file based on a value in a C# Setting class. This value however changes from machine to machine and Id rather not ask the user the first time the program is run as its a corporate environment, instead Id like it to be set in the installer, but where is the file located? Is there an easier method?
This is a visual studio addin not a standalone program
From your post it appears you have a windows application? , you can store an initial value in the application config, you can make an installer in Visual Studio and write custom actions that can write values to the file on first install in you install project.
The configure file is the easiest way to do what you are asking, however it is NOT the best. In fact it is recommended Not to use .config files for such cases.
whenever users install an 'update', there is a risk of overwriting their existing changes.
some businesses might have policy restrictions on the .config files.
the user cannot easily move his settings from one PC to another.
From my own experience, using XML, MS-Access, Registry or text files to store user settings has proven more useful than using the .config files.
I believe you are talking about designer-generated settings (the .settings file)?
The exact path usually contains some sort of a Hash (check this link). I usually have my own settings class which I serialize to and from xml using XmlSerializer, which gives me more freedom (I think C# settings files don't allow you to add custom enums, for example, or they make it a bit harder to do it than simply adding them to the .settings file).
However, maybe there is no need to set values during installation? For example, you could add a FirstStartup setting (set to true initially), which you can read when your App is started for the first time, and then set it to false. That way you can set your default settings when you detect a "first startup".
You will certainly need some sort of custom action at the end of your installer. You haven't mentioned what technology you're using to deploy your application so I will refrain from giving any specific guidance.
I recommend setting the value in your App.config. This is an xml file which will be named MyApplication.exe.config in the same directory as your application. Add it to your installer if it is not there already. In your installer, add a new setting:
<configuration>
<appSettings>
<add key="MySetting" value="My Value"/>
</appSettings>
</configuration>
In your code, retrieve the setting:
String setting = ConfigurationSettings.AppSettings["MySetting"];
If this is a machine-wide setting, this installer is the right place to set this. If you do it on the first execution you will run into a host of problems with permissions on the files and directories if the first person to run the app is a user with limited permissions.
Registry or an INI file or a XML file whatever suits you best.
Best option would be registry. Istalling the application will require Admin access so writing to the registry during installation will not be an issue.
More over if some one accidently deletes the ini or settings file then the program might stop working.
You said that this is for a corporate environment. You can create an administrative template for group policy to set the default in the registry. Then, your program can just query that one registry value if the default hasn't already been set.
I personally would never use web.config or app.config. Just read your own xml file, have a look at my post on this:
http://www.picnet.com.au/blogs/Guido/post/2009/09/10/XML-Settings-Files-No-more-webconfig.aspx
Thanks
Guido
To answer the "Where is the file located" bit of the original question for those interested (I'm assuming that the "settings file" in question is the "Settings File" item available from the "Add New Item" dialogue).
In Win7 (and probably all the other ones) the settings file will generate under the path:
C:\Users\[user]\AppData\Local
The folder structure from here on out depends on your AssemblyInfo and build information, the "AssemblyCompany" field (if populated) is used for the top-most folder, beneath this is a folder copying the application executable name, followed by the build and then finally the settings file (named "*.config").
In my case, the complete path is as follows:
C:\Users\[user]\AppData\Local\[company_name]\Application.exe_StrongName_zx0v1qxyoass4d0z3mtwe3vbrhaehkjg\0.0.5812.21662\user.config
My case is different, my project is a class library (dll) which have the app.config file. I decided to create 4 application settings variables (title, url, limit, rate). To create this, i right-click ont he project --> Properties --> Settings. this values you can retrieve in code using this command --> Settings.Default.title, ...etc
the problem is let say i instantiate 5 objects (same object for example MyProject.MyClass) from this library, i want the instance be able to have its own settings. i mean each of the instance may have their xml setting file. can this be done?
Related
In several C# projects I have been using an app.config file to pass various settings to my program, settings like connectionstrings, power levels etc.
However sometimes I have come in situations where the settings aren't updated as expected and I have concluded that I am not that well informed with the proper use of app.config file.
Example:
Replacing the .exe file with a new version (where settings are different) to the output directory without changing the exe.config, results in the program seeing the hard-coded settings and not the settings of the existing .exe.config
So my Questions are:
What is the exact role of exe.manifest file
Every time I create a new .exe do I have to paste in the output folder anything else except the .exe file?
Whats the difference in obtaining the setting value by: ConfigurationManager.'settingName'... rather than:
Properties.Settings.Default.'settingName'?
What is the role of app.config build action?
Sorry If I am asking too much in a single Question.
The app.config file is a file that gets a special treatment when running the associated application. If you executable is named MyApp.exe the app.config file should be named MyApp.exe.config. The role of the app.config build task is to copy the file named app.config in your project to MyApp.exe.config in the output directory.
.NET provides ways to read the contents of the file (it is in XML format) and various parts of .NET will look for different sections in this XML to provide configuration.
A widely used section is the settings section you refer to as Properties.Settings.Default. This section plays together with Visual Studio that provides an editor for application settings. The settings are accessed in the code by using a generated class. Adding a setting will add a property to this class and this property is initialized from a value in the app.config file.
In the Visual Studio editor you can set a value for the setting and you can think of this as a default value for the setting. However, if you overwrite the value in the app.config file the later will take precedence. This allows you to modify the app.config file after installation and rerun the application with a modified setting.
You can also access application settings the app.config file using other methods, but in my oppinion using the Visual Studio editor and the code generated class is the best way to do that.
I am not sure I fully understand the problem that you experience. If you update MyApp.exe and leave MyApp.exe.config intact you should not see a change in the settings used by the application (unless of course you have renamed or changed some settings).
The manifest file provides information about side-by-side assemblies and can be used to request elevated privileges among other things. This is not related to the app.config file.
There quite a few resources about that.
See http://msdn.microsoft.com/en-us/library/ms229689%28v=vs.90%29.aspx
and the (better) overview: http://msdn.microsoft.com/en-us/library/k4s6c3a0%28v=vs.110%29.aspx
app.config is a very powerful tool. It addresses many issue like versioning, migration, upgrading etc. but this requires some in-depth reading from the links above.
Maybe one thing you could do, if you want to copy only .exe file every time you build your app, is make a settings.ini or settings.txt file, put your parameters in this file (that are not secret of course) and read all your settings from there when you start your app.
You can put all your connection string logic in your login form if you have one...
Kind of a two part issue.
I developed an app which reads from and writes to an App.config.
The application is installed in Program Files by my MSI installer.
It works fine on my Win7 computer but I have users on Win7 that get Access Denied when writing to this App.config.
I am writing to the app.config using the below code:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["Endpoint"].Value = endpointTxtBox.Text;
config.Save(ConfigurationSaveMode.Modified);
Why don't I get this issue on my development pc? I have tried both with a local admin and normal local user account.
How do I relocate the App.config to an unprotected directory?
Cathal,
You should not have to move the app.config in order to let your users save their application settings; .NET already has support for saving user-scoped app settings in user-writable storage baked in! You can even specify the default user settings in the app.config file.
Check this link for details:
http://msdn.microsoft.com/en-us/library/8eyb2ct1(v=vs.110).aspx
Note that making use of a strongly-typed .NET Settings class rather than the raw, more weakly-typed AppSettings NameValueCollection. (The settings can still stored in the app.config, though.)
You can create a Settings file in VS (the template is called "Settings file" in VS).
A couple of things confused me about Settings files at first, so I thought I would point them out to you:
1) First: the .settings file. The VS designer lets you define your app settings, their types, and their scopes (i.e. user or application). This is the file the designer modifies when you user the designer, but runtime configuration changes will never be written to this file. It defines your app settings and their default values. That's it. I didn't get that at first when I was trying to wrap my head around Settings files.
Also, notice that the build action on the .settings file is set to SettingsSingleFileGenerator.
2) The .designer.cs file. VS/MSBuild generates this file at build-time for you because the build action on the .settings file is set to SettingsSingleFileGenerator. The class that it generates is a strongly typed wrapper for your configuration properties, and you can use it equally well for your application-scoped and user-scoped properties.
3) The runtime settings that your Settings class wraps are still stored in the app.config.
4) User settings are stored underneath that user's AppData\Local directory so that they have full read/write permissions.
I had a couple of other ideas, if what you need to do really is let the user modify the global application settings for all users.
Externalize some of your configuration by using the configSource attribute. You store the entire
appSettings section, for instance, in a separate file by doing this:
<appSettings configSource="....\file.config" />
Here are the docs for that feature: http://msdn.microsoft.com/en-us/library/ms228154(v=vs.85).aspx
I believe you can manually load a config file anywhere you want using the System.Configuration.ConfigXmlDocument class. Construct one using the no-arg constructor and then call its Load(String filename) method.
Store your configuration in the registry rather than the filesystem by implementing a custom SettingsProvider.
For testing and debugging purposes, I just hard-coded the file paths for the text files that would be used by my application, e.g.
const string CONFIG_FILE_PATH = #"C:\myconfigfile.txt";
But I don't think it's a good idea to leave it as it is in the Beta/Release version.
So I am wondering, what would be the best location for saving these configuration files that will be used / read by the application? Any suggestions?
Many Thanks.
Why not save the strings in the Settings section of your project? GRight click on your project in Solution Explorer, select Properties, go to the Settings section and add a new string with your file path. Then, in your code, you can access it like this:
using ProjectName.Properties;
var path = Settings.Default.MySetting;
To change the setting:
Settings.Default.MySetting = newPath;
Settings.Default.Save();
In the same folder as the executable.
But you should consider using a Settings class (you can read more here). Visual Studio can automatically create a strongly typed wrapper around a section in the app.config file.
The settings are stored in the same file as the executable, but can be overridden (and saved from the application) in a matching file in the user profile for each user.
Another option: If the test config file is intended to sit along side your executable, you can "Add" "Existing Item..." to your project and then change its properties to "Copy always" or "Copy if newer". During debugging, the executable should be able to find the copy of the config in its current working directory.
This isn't such a useful solution when there's a lot of testing to do.
For settings I would certainly use the app.config file. This is proposed by Microsoft and apart from that it is pretty much the easiest way to handle application settings anyway.
For other files I'd recommend either the applications local or roaming settings path, depending on weather you only need the data local or not. For compact, local databases I tend to use this approach. The application directory, as suggested by Albin, is a bad idea. You cannot be sure that the user is actually allowed to write to that directory and/or files in that directory (i.e. the app was pre-installed by an admin with elevated rights).
To get the location of the local paths use
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal)
and for the roaming path
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming)
More information on Windows User Profiles (the actual paths in different versions of Windows for example, you can find here: http://msdn.microsoft.com/en-us/library/aa372123.aspx
I'm using setting from my C# application like this:
String str = Properties.Settings.Default.SETTINGS_NAME;
When I save this settings, a settings file is created on
C:\Documents and Settings\<user name>\Local Settings\Application Data\<comp name>\Keb.exe_Url_pbs4eg1o2ija22omldrwjxhdam0jxxi5\1.0.0.0\user.config
Is there a way to change this path to Application.ExecutablePath\user.config, and use it next time so my application can be more portable ?
You can control the location of the user.config file by creating a custom SettingsProvider. Luckily for you, someone at CodeProject already did that.
See my answer here for all the details: How to make designer generated .Net application settings portable
If you want it to be Single user or in other way make the configuration of your application portable i will use a custom config file like an .ini file and keep it my app's root folder.
That way any one want to have those settings can just copy it in his own app's root folder on some other computer. When app runs it just loads the settings and behave accordingly.
save data in a fixed format like
[setting_name] = [Setting_value]\n
or in XML file, with Tag name for setting and value for... well... value :)
You can also go with registry setttings but user don't feel it trivial to copy and merge .reg files
This is the way i have seen some PC Games (for eg. i frequently changed Crysis and MassEffect settings) and Softwares save their config files.
I'm working on an installer project, during the install process I'd like the user to create a "root" account. I'd like to have the root password become a part of the app.config's file, preferably the encrypted section. Is such a thing possible? Are there any known solutions to this problem?
Best regards
Yes, you can. The App.Config is nothing more than an XML file. After you place the app.config in the appropriate place in the installation process, just create an action (either execute a program or a script) in the installer which updates the app.config with the appropriate value.
Custom Actions:
http://msdn.microsoft.com/en-us/library/aa368066(VS.85).aspx
Executing a program with a custom action:
http://msdn.microsoft.com/en-us/library/aa368563.aspx