Where are config files for class libraries physically located? - c#

My guess is that this question will fall under the category of "duh", but, nevertheless, I'm confused.
When using config files in, for example, a Windows Forms Application, the config file can be found in C:\Program files\CompanyName\ProductName\Application.exe.config. However, with the class library I'm developing I do not see a "ClassLibrary.dll.config" file in the install folder after installing it (in tandem with another project) from Visual Studio. Even though I do not see the file anywhere, retrieving data from it works correctly. Plus, running the following code from a method within the class library returns the path you would expect: C:\Program files\CompanyName\ProductName\ClassLibrary.dll.config.
If someone could shed some light on what I'm missing here, that would be really awesome.
public static string MyMethod()
{
Assembly assem = Assembly.GetExecutingAssembly();
Configuration config = ConfigurationManager.OpenExeConfiguration(assem.Location);
return "The assembly location was: " + assem.Location + Environment.NewLine +
"The config file path was: " + config.FilePath;
// Gives me "C:\Program files\CompanyName\ProductName\ClassLibrary.dll.config"
}

In a class library, the app.config file is pretty useless. Application setting values get stored in the Settings.settings file and are compiled into the Settings.designer.cs file.
If you modify the value of one of your application settings in app.config directly, that won't have an effect on the setting value seen while running the application. You have to actually open the Settings editor, at which point it will notice the difference between the app.config file and the Settings.settings file and inquire as to whether you'd like it to update your Settings.settings file using values from app.config.

Depends on the version of .NET. Prior to .NET 4.0, class libraries cannot use their own app.config files unless you do custom stuff to read the data in. In these scenarios, you should have the initialization of your class libraries require all of the appropriate data and pass that in from your consuming class's configuration (i.e. ultimately your winform's app.config file).

Your class library will use the config file of the executable that called it.

Your default value is stored in the dll.
But let's say you change the setting in code and save it. Where does it get stored for next time?
In WinXP look in:
C:\Documents and Settings\username\Local Settings\Application Data\
or in Windows Vista/7 look in:
C:\Users\username\AppData\Local\
You will find a folder named after your application and drilling down in to that folder, you will find a file named user.config.
For example:
C:\Documents and Settings\username\Local Settings\Application Data\MyApp\myapp.exe_urlla1ii3sytrhx0adqtjnjuc24oacqpgu4\1.0.0.0\user.config

Just to expand on #TLiebe's answer here, it is stored in the main assembly's settings file under a separate domain. For example:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<TestLib.Properties.Settings>
<setting name="TestSetting" serializeAs="String">
<value>2.8.0.0</value>
</setting>
</TestLib.Properties.Settings>
<UpdateTest.Properties.Settings>
<setting name="Token" serializeAs="String">
<value>{fV234hwolihj453lvB}</value>
</setting>
</UpdateTest.Properties.Settings>
</userSettings>
</configuration>

Related

What is App.config in C#.NET? How to use it?

I have done a project in C#.NET where my database file is an Excel workbook. Since the location of the connection string is hard coded in my coding, there is no problem for installing it in my system, but for other systems there is.
Is there a way to prompt the user to set a path once after the setup of the application is completed?
The answers I got was "Use App.Config"... can anyone tell what is this App.config and how to use it in my context here?
At its simplest, the app.config is an XML file with many predefined configuration sections available and support for custom configuration sections. A "configuration section" is a snippet of XML with a schema meant to store some type of information.
Overview (MSDN)
Connection String Configuration (MSDN)
Settings can be configured using built-in configuration sections such as connectionStrings or appSettings. You can add your own custom configuration sections; this is an advanced topic, but very powerful for building strongly-typed configuration files.
Web applications typically have a web.config, while Windows GUI/service applications have an app.config file.
Application-level config files inherit settings from global configuration files like machine.config. Web also applications inherit settings from applicationHost.config.
Reading from the App.Config
Connection strings have a predefined schema that you can use. Note that this small snippet is actually a valid app.config (or web.config) file:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Once you have defined your app.config, you can read it in code using the ConfigurationManager class. Don't be intimidated by the verbose MSDN examples; it's actually quite simple.
string connectionString = ConfigurationManager.ConnectionStrings["MyKey"].ConnectionString;
Writing to the App.Config
Frequently changing the *.config files is usually not a good idea, but it sounds like you only want to perform one-time setup.
See: Change connection string & reload app.config at run time which describes how to update the connectionStrings section of the *.config file at runtime.
Note that ideally you would perform such configuration changes from a simple installer.
Location of the App.Config at Runtime
Q: Suppose I manually change some <value> in app.config, save it and then close it. Now when I go to my bin folder and launch the .exe file from here, why doesn't it reflect the applied changes?
A: When you compile an application, its app.config is copied to the bin directory1 with a name that matches your exe. For example, if your exe was named "test.exe", there should be a ("text.exe.config" in .net framework) or ("text.dll.config" in .net core) in your bin directory. You can change the configuration without a recompile, but you will need to edit the config file that was created at compile time, not the original app.config.
1: Note that web.config files are not moved, but instead stay in the same location at compile and deployment time. One exception to this is when a web.config is transformed.
.NET Core
New configuration options were introduced with .NET Core and continue with the unified .NET (version 5+). The way that *.config files works hasn't fundamentally changed, but developers are free to choose new, more flexible configuration paradigms.
As with .NET Framework configuration .NET Core can get quite complex, but implementation can be as simple as a few lines of configuration with a few lines of c# to read it.
Configuration in ASP.NET Core
Configuration in .NET Core
Simply, App.config is an XML based file format that holds the Application Level Configurations.
Example:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="key" value="test" />
</appSettings>
</configuration>
You can access the configurations by using ConfigurationManager as shown in the piece of code snippet below:
var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"
Note: ConfigurationSettings is obsolete method to retrieve configuration information.
var value = System.Configuration.ConfigurationSettings.AppSettings["key"];
App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
See this MSDN article on how to do that.
Just to add something I was missing from all the answers - even if it seems to be silly and obvious as soon as you know:
The file has to be named "App.config" or "app.config" and can be located in your project at the same level as e.g. Program.cs.
I do not know if other locations are possible, other names (like application.conf, as suggested in the ODP.net documentation) did not work for me.
PS. I started with Visual Studio Code and created a new project with "dotnet new". No configuration file is created in this case, I am sure there are other cases.
PPS. You may need to add a nuget package to be able to read the config file, in case of .NET CORE it would be "dotnet add package System.Configuration.ConfigurationManager --version 4.5.0"
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
Just adding one more point
Using app.config some how you can control application access, you want apply particular change to entire application use app config file and you can access the settings like below
ConfigurationSettings.AppSettings["Key"]
Application settings enable you to store application information dynamically. Settings allow you to store information on the client computer that shouldn't be included in the application code (for example a connection string), user preferences, and other information you need at runtime.
To add an application configuration file to a C# project:
In Solution Explorer, right-click the project node, and then select Add > New Item.
The Add New Item dialog box appears.
Expand Installed > Visual C# Items.
In the middle pane, select the Application Configuration File template.
Select the Add button.
A file named App.config is added to your project.
take a look at this article

I need my C# settings file to be static (as in one place)

Currently I have the the default Settings.settings file that I access through Properties.Settings.Default.
But this config is saved in my user's appdata folder. How can I get there to be only one config file kept in the same dir as the exe that is universal AND can be changed at runtime?
You can't do this with the Properties.Settings feature, as the documenation says:
Application-scope settings are read only, and can only be changed at
design time or by altering the .exe.config file in
between application sessions. User-scope settings, however, can be
written at run time, just as you would change any property value. The
new value persists for the duration of the application session. You
can persist changes to user settings between application sessions by
calling the Settings.Save method. These settings are saved in the
User.config file.
An alternate approach would be to use the System.IO API to read and write a configuration file you design yourself.
You're gonna have problems with UAC on Vista/7.
Please, do keep vital application data files such as the "Settings" in a hidden and accessible directory - AppData.
UAC allows access to this directory and it's subdirectories.
If you want to share the file among all the users, you might want to use the "CommonAppData" directory, but you need administrator rights to write there.
You can place the settings in the application configuration file in the <applicationSettings> tag.
See http://msdn.microsoft.com/en-us/library/ms229207.aspx for documentation on the tag.
Eg (xxxxx -> the Visual Studio project name, yyyyy-> actual setting in the Settings file).
<applicationSettings>
<xxxxxx.Properties.Settings>
<setting name="yyyyyy"
serializeAs="String">
<value>some_value</value>
</setting>
</ReprintProcess.Properties.Settings>
</applicationSettings>
You cannot achieve it without extending and heavily modifying Properties.Settings class.
Therefore I would recommend either writing your own Settings Management wrapper or alternative libraries such as Settings4Net

Where are the Properties.Settings.Default stored?

I thought I knew this, but today I'm being proven wrong - again.
Running VS2008, .NET 3.5 and C#. I added the User settings to the Properties Settings tab with default values, then read them in using this code:
myTextBox.Text = Properties.Settings.Default.MyStringProperty;
Then, after the user edits the value in the options dialog I save it like this:
Properties.Settings.Default.MyStringProperty = myTextBox.Text;
Properties.Settings.Default.Save();
My question is, where is this new value saved? the MyApp.exe.config file in the executable directory is not updated, it still contains the default values. Plus, as far as I can tell, none of the other files in that directory are updated either! However, when the program reads the value back in, it gets the changed value, so I know it's saved somewhere...
This isn't just academic, I needed to be able to manually edit the value this morning and got myself stumped when I couldn't find anything that was changing.
In order to work with newer versions of Windows' policy of only allowing read access by default to the Program Files folder (unless you prompt for elevation with UAC, but that's another topic...), your application will have a settings folder under %userprofile%\appdata\local or %userprofile%\Local Settings\Application Data depending on which version of Windows you're running, for settings that are user specific. If you store settings for all users, then they'll be in the corresponding folder under C:\users or C:\Documents and Settings for all user profiles (ex: C:\users\public\appdata\local).
You can get the path programmatically:
using System.Configuration; // Add a reference to System.Configuration.dll
...
var path = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;
thanks for pointing me in the right direction. I found user.config located at this monstrosity:
c:\users\USER\AppData\Local\COMPANY\APPLICATION.exe_Url_LOOKSLIKESOMEKINDOFHASH\VERSION\user.config.
I had to uprev the version on my application and all the settings seemed to have vanished. application created a new folder with the new version and used the default settings. took forever to find where the file was stored, but then it was a simple copy and paste to get the settings to the new version.
it is saved in your Documents and Settings\%user%\Local Settings\Application Data......etc search for a file called user.config there
the location may change however.
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>
One of my windows services is logged on as Local System in windows server 2016, and I can find the user.config under C:\Windows\SysWOW64\config\systemprofile\AppData\Local\{your application name}.
I think the easiest way is searching your application name on C drive and then check where is the user.config
They are saved in YOUR_APP.exe.config, the file is saved in the same folder with YOUR_APP.exe file, <userSettings> section:
<userSettings>
<ShowGitlabIssues.Properties.Settings>
<setting name="SavedUserName" serializeAs="String">
<value />
</setting>
<setting name="SavedPassword" serializeAs="String">
<value />
</setting>
<setting name="CheckSave" serializeAs="String">
<value>False</value>
</setting>
</ShowGitlabIssues.Properties.Settings>
</userSettings>
here is cs code:
public void LoadInfoLogin()
{
if (Properties.Settings.Default.CheckSave)// chkRemember.Checked)
{
txtUsername.Text = Properties.Settings.Default.SaveUserName;
txtPassword.Text = Properties.Settings.Default.SavePassword;
chkRemember.Checked = true;
}
...
User-specific settings are saved in the user's Application Data folder for that application. Look for a user.config file.
I don't know what you expected, since users often don't even have write access to the executable directory in the first place.
For anyone wondering where the settings for apps from the Microsoft Store are, they are either in WindowsApps, which is very locked down, but you can get there by opening your app and then opening the file path with Task-Manager.
But it's more likely that they are saved in C:\Users\[USERNAME]\AppData\Local\Packages\[NUMBERS][COMPANY].[APPLICATION]_[RANDOMDATA]\LocalCache\Local\[COMPANY]\[APPLICATION].exe_Url_[RANDOMDATA]\[VERSION]\user.config.
There is a folder called "Properties" under your project root folder, and there are *.settings file under that folder. That's where it gets stored.

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.

App.config for dll

We have an "engine" that loads dlls dynamically (whatever is located in a certain directory) and calls Workflow classes from them by way of reflection.
We now have some new Workflows that require access to a database, so I figured that I would put a config file in the dll directory.
But for some reason my Workflows just don't see the config file.
<configuration>
<appSettings>
<add key="ConnectString" value="Data Source=officeserver;Database=mydatabase;User ID=officeuser;Password=officeuser;" />
</appSettings>
</configuration>
Given the above config file, the following code prints an empty string:
Console.WriteLine(ConfigurationManager.AppSettings["ConnectString"]);
I think what I want is to just specify a config filename, but I'm having problems here. I'm just not getting results.
Anyone have any pointers?
If your code sample for reading the AppSettings is in your DLL, then it will attempt to read the config file for the application and not the config file for the DLL. This is because you're using Reflection to execute the code.
Funny, where I'm at we're doing something very similar and the config file loads just fine. In our case I think each new config file's name matches that of it's associated assembly. So MyLibrary.dll would have a file named MyLibrary.dll.config with information for that file assembly. Also, the example I have handy is using VB.Net rather than C# (we have some of each) and all the settings in there are for the VB-specific My.Settings namespace, so we don't use the ConfigurationManager class directly to read them.
The settings themselves look like this:
<applicationSettings>
<MyLibrary.My.MySettings>
<setting name="SomeSetting" serializeAs="String">
<value>12345</value>
</setting>
</MyLibrary.My.MySettings>
</applicationSettings>
I wrote this for a similar system. My recollection is that I used Assembly.GetExecutingAssembly to get the file path to the DLL, appended .config to that name, loaded it as an XmlDocument, navigated to the <appSettings> node and passed that to a NameValueSectionHandler's Create method.
Here is one way -
AppDomain.CurrentDomain.SetData ("APP_CONFIG_FILE", "path to config file");
Call in constructor.
If I recall correctly, the app.config will be loaded from your application directory, so if you are loading dlls from some other directory, you'll want the keys they need in your application's config file.
I'm not totally sure but I think that class only works with the path of the entry method of the AppDomain (the path of the exe most of the time) by default.
You need to call OpenExeConfiguration(string exePath) (Framework 2.0 and later) first to point to a different config file.

Categories

Resources