.NET C# executable is not reading config dynamically - c#

In my app.config i got something like:
<appSettings configSource="AppSettings.config"/>
I would have expected the application to read the settings dynamically from AppSettings.config but i doesn't...
Am i wrong here?

app.config is read once at startup. Re-reading each time a config value is referenced could be a big performance hit. Besides, there are some entries like dependencies that it wouldn't make sense to change at runtime.

You are using the wrong attribute, use the file attribute to reference an external configuration file:
<appSettings file="AppSettings.config"/>

The Setting is correct. But as ctford said, this is only read once, when the application starts up... Is the file in the same folder as the application executable is being loaded from ? Also, in Visual Studio, where you have the file stored, right click on it, and verify that you have the Visual Studio File property "Copy to Output Directory" set appropriately. For files like this, the default is "Do Not Copy" and then the file will, duh, not be there when the app runs and looks for it...

Related

Using app.config correctly

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...

Why my changes of AppSettings in App.config is not taken into account in run-time? (Console Application)

I have a console application which has its own App.config.
I need to change some values in section time to time.
My problem is, when I execute the exe within the bin/debug folder it gets the relevant appsettings correctly. But when I edit and change values of some key/value pairs and RE-RUN the exe, it still reads the original values.
(By RE-RUN I mean running the application on the command promt by calling MyTool.exe)
I tried to call
ConfigurationManager.RefreshSection("appSettings");
in the begining of my Main method. But did not help.
Can you please advise?
Thanks
But when I edit and change values of some key/value pairs and RE-RUN
the exe, it still reads the original values.
Depends how you are RE-RUNNing this exe. If you are doing this in Visual Studio, by hitting F5, VS simply copies the app.config file in your project to the output and renames it to AppName.exe.config. So if you want your changes to be taken into account you have to modify AppName.exe.config (not App.config) and then run the executable from the Windows Explorer.
This being said, the App.config is read and parsed only once. When the application starts. The values are then cached to avoid expensive XML parsing everytime your application requests some value.
App.config is designed to store configuration values that are not supposed to be changed. If you need to change configuration values dynamically you should use some other storage mechanism: file, database, ...
But the ConfigurationManager.RefreshSection("appSettings"); method should work. Once you have modified the AppName.exe.config file, you call this method and then refetch the value you need using ConfigurationManager.AppSettings["someKey"]; which should return you the new value.
For me I had to manually delete the application.exe.config located in /obj/Debug/ as this was basically acting like a cache. So anytime I would edit my app.config, (re)build, but looked at the application.exe.config, it was not fully updated after the build. Doing the above allowed me to force the IDE to recreate the application.exe.config in the /bin/
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// change ConnectionString in App.Config for Entity FrameWork Object....
//.....
config.Save();
are you save config file?

Rename app.config to dllname.dll.config

I have a class library, which has an app.config and when built it put the app.config along with the dll in the output directory I have chosen.
I don't want it to be name app.config though, if I have another component that has it's own dll, I can see confusion happening.
I've been looking at another project, that does exactly that, but I can't see why it outputs dllname.dll.config and mine always app.config.
Any ideas?
Thx
You probably have set the Copy to output directory setting of the app.config.
BUT: In a class library, an app.config is useless.
Note, that you can only have one config file per application. The configuration is being read (at execution time) from <executing assembly file name> + ".config".

C# Settings xml file location

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?

Windows Service Config File C#

I've developed a windows service application using Visual Studio 2008 / C#.
I have an app.config file in the project. When installed, the app.exe.config file appears beside the executable but it appears not to be reading the values from it when I try to access them through ConfigurationManager.AppSettings.
Has it copied the config file elsewhere or is there some other problem I don't know about?
Thanks in advance,
Martin.
Edit:
The config file name is infact my_exe_file_name.exe.config, it looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="RuntimeFrequency" value="3" />
</appSettings>
</configuration>
and I am trying to read via:
ConfigurationManager.AppSettings["RuntimeFrequency"]
The debug value I continually see is '1' and not '3'. Am I doing something wrong here?
I located the error and it was related to file permissions. After installing the service, my local user account didn't have access to modify the app.exe.config file.
The tool I was using to edit was not informing me it was being denied access to save the file - that's notepad++ if anyone is interested - so I couldn't see that it wasn't saving over the old config file.
Solved now, thanks everyone.
Martin.
When you are in debug mode check and see what settings are in the my_exe_file_name.vshost.exe.config Also make sure you adjust this in the app.config file. Visual studio should update the final config file in your bin/debug folders.
Maybe you are updating the wrong config file. You should double check that using
System.Configuration.ConfigurationManager.OpenExeConfiguration(PATH_TO_CONFIG);
Generally for the Windows Services that I write, i drop the appName.exe.config file into C:\WINDOWS\system32\
Perhaps you have an older version in that directory, which is where your service is getting the value, even though you've updated the config file in your project.
App.config file should be renamed to your_exe_file_name.exe.config and placed near the exe file.
Is it possible that you have more than one instance of the RuntimeFrequency entry defined? The ConfigurationManager reads the file from top to bottom and processes each setting individually. Therefore, the last value of RuntimeFrequency that is defined in the file is the one it will use.
If you want to know for sure if your file is being used, I would simply remove or comment out any definition for RuntimeFrequency (copy/paste errors do happen) and wait to see an application error when ConfigurationManager attempts to reference an entry in AppSettings that does not exist.

Categories

Resources