I'm new to C#. In the past projects I have worked on, I inherited code where the user already created some default config file system to allow a user to be able to input their own settings outside of the developer environment. Where all they need is the exe and config file which they can edit.
I am writing a simple file copier application and it dawned on me that the two projects I've worked on the users went out of their way to write their own way to use config files. To save time, I looked and saw that Visual Studio gives you a default app.config file to use. So I tried to use it.
My issue:
I have this bit of code:
public static void GetBaseSoureDirSubFolders()
{
BaseSourcePath = ConfigurationManager.AppSettings.Get("BaseSourcePath");
Console.WriteLine($"Base Dir Is: { BaseSourcePath}");
DirectoryInfo dirInfo = new DirectoryInfo(BaseSourcePath);
BaseSubFolders = dirInfo.GetDirectories();
}
When I run the code inside visual studio with my appconfig file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
<appSettings>
<add key="BaseSourcePath" value="C:\TDX2KlarfOutputs\"/>
<add key="share" value="\\cdserver.com\share\"/>
<add key="UserCount" value="2"/>
</appSettings>
</configuration>
it does return the value I have inside the file that I wrote in Visual studio.
The problem happens when I take the exe file and the app.config file and put it in the location I want to run this code. When I run the code, it gives me C:\TDX2KlarfOutputs\ instead of the new value I put inside app.config for that BaseSourcePath. It still uses the one I set in Visual studio.
THings I have tried:
I have set it to app.config properties to Build Action =content and CopytoOutputDirector = copy if newer.
I have tried using this in my main() function :
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", #".\App.config");
But this doesn't work. I am very new to C# so I'm probably not using the right terminology to describe the issue. The issue is, how can I make my console app, use values set by user on their copy of app.config file outside of Visual studio's values?
I have tried to google this but maybe due to my lack of experience I cannot find a question that answers my issue.
I think you are not using the compiled app.config but instead the uncompiled file.
If your program (.exe) name is copier, it should create a copier.app.config file.
Try to edit that.
Hope my answer helps you
Here, the folder contains two files through which I can access the code of the project in visual studio: Program.cs & ProgrammingAssignment3.csproj
When I open the Program.cs file there is no Solution Explorer, which helps in accessing different custom classes.
Even if I tried adding it from the View window:
It doesn't show anything inside it.
I also tried Tools < Options < Projects and Solutions but there's no changes.
But here when I open this .csproj file:
The solution explorer is shown and also the classes.
But unfortunately, as I need program.cs file for my work, I can't use the .csproj file. And this not just for this project but every other too. Please tell me how should I get appear the Solution explorer in the program.cs file so that I can write code easily by accessing the classes. I don't mean I've problem with the .csproj file, I want the solution explorer to get running in program.cs file.
The class (.cs) is in your project (.csproj), and the project is always in a solution (.sln). The solution isn't accessible when its part of your Unity project.
If you open the project file directly from the file explorer you can edit the class program.cs from there.
You could also open the script from Unity itself and it brings you there too.
check if you multiple installation for VS
go to environment varaible and remove if you have duplicate entiries of old one
follow below steps:
tool Menu-->Import Export Setting--> Reset All setting --> Next ---> No Just reset my setting --> Next--> general development setting --> finish
it should fix the issue
I have a C# console app. It reads values from App.config.
Within App.config I make use of the file property of the appSettingssection.
In this way I can have a secondary configuration file that should supplement/overwrite properties defined in the primary configuration file.
However I find that the properties in the secondary file are not available at run time.
App.config (extract)
<appSettings file="App-not-in-source-control.config">
<add key="THIS_IS_A_TEST_KEY" value="Test Value" />
....
</appSettings>
App-not-in-source-control.config
<appSettings>
<add key="SOMEVALUE" value="foobar"/>
</appSettings>
Program.cs (Extract)
//THIS WORKS
var only4dbg = ConfigurationManager.AppSettings["THIS_IS_A_TEST_KEY"].ToString();
//THIS DOESNT WORK
var someValue = ConfigurationManager.AppSettings["SOMEVALUE"].ToString();
The attempt to read SOMEVALUE results in the following exception
Unhandled Exception: System.NullReferenceException:
Object reference not set to an instance of an object.
Is there something I've overlooked here ?
OK well having written that all out I realised what the problem was.
The secondary config file is only available to the run time if you've set the 'Copy to Output Directory' property of the file to something other than 'Never' ('Never' is the default setting).
It's strange to me that 'Never' is the default setting ; it's not the case for the 'App.config' and the secondary config (at least in my case) was created using the 'Add | New Item | Application Configuration File' dialog sequence within 'Solution Explorer' - there doesn't seem to be much point asking Visual Studio to create a config file which isn't going to be available to the project build output.
Regardless that's the way it is - hope this helps someone else.
I have a C#/.NET Winforms application which has some settings stored using A '.settings' file. So the configuration is edited by right-clicking the project in "Solution Explorer" and selecting "Properties->Settings".
However, I also need to be able to catch exceptions thrown by a SerialPort object inside the application. I found a snippet on the web stating that adding
<runtime>
<legacyUnhandledExceptionPolicy enabled="1"/>
</runtime>
... in the app.config file would fix this (which it did). BUT: Now a have both a "Settings.settings" and an "app.config" file in my Solution Explorer, which causes some developers to edit e.g. "app.config" and not "Settings.settings" causing much confusion. Is it possible to make the "Settings" class generate the 'legacyUnhandledExceptionPolicy'-thingy the app.config file automatically? Or what else should I do? Any suggestions?
I'll simply conclude that This can't be done.
I want to use a single app.config by 3 different projects.
How to access the configurations?
ConfigurationManager.AppSettings["config1"]
Let's say you have this folder structure:
Solution
Project1
Project2
Project3
Do this:
Create the App.config file in the Solution level folder. You won't find an option to add an App.config file from the templates, so just create a new empty text file with the name App.config, and paste in the contents of a regular App.config file.
For each project in Solution Explorer:
Right click and select Add > Existing Item
Locate the file
Select Add as link from the drop down box next to the Add button.
Edited to add:
You correctly state that the above method only shared the file up to build-time. To use a shared file at run-time, see the answers to this question.
The common config file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section
name="appSettings"
type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
/>
</configSections>
<appSettings>
<add key="key1" value="value1"/>
</appSettings>
</configuration>
To access mapped config file
ConfigurationFileMap fileMap = new ConfigurationFileMap(file); //Path to your config file
Configuration configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
string value = configuration.AppSettings.Settings["key1"].Value;
I have found the button, and opened
the app.config as link, however that
caused when build to again create
separate config file for each project,
and therefore, when deploying the 3
project, i will have 3 config files.
What I wanted to do, is keeping a
single file for all projects in a
certain solution. Can I do that?
Yes - you can do it, but should you do it?
The basic assumption in a .NET app is that one app = one config file. Out of the box, and with an easy method, you cannot share config files between applications.
If you create your own custom config sections, you could "outsource" those to external files, which could be shared. Imagine you create your own custom config section called "MyConfiguration", then your app.config would look something like that:
<configuration>
<configSections>
<section name="MyConfiguration"
type="MyConfigurationSection, MyConfigurationAssembly" />
</configSections>
<MyConfiguration>
<nestedElement>
<dateTimeValue>10/16/2006</dateTimeValue>
<integerValue>1</integerValue>
</nestedElement>
</MyConfiguration>
</configuration>
You could have your "MyConfiguration" section in its own file, and reference it from your app's config:
<configuration>
<configSections>
<section name="MyConfiguration"
type="MyConfigurationSection, MyConfigurationAssembly" />
</configSections>
<MyConfiguration configSource="MyConfiguration.config" />
</configuration>
and your "MyConfiguration.config" would then contain:
<MyConfiguration>
<nestedElement>
<dateTimeValue>10/16/2006</dateTimeValue>
<integerValue>1</integerValue>
</nestedElement>
</MyConfiguration>
By doing this, you could "externalize" and thus share at least the bulk of your config settings - provided they're in your own custom config sections.
For more info and an excellent intro to .NET 2.0 and up configuration mysteries, see Jon Rista's three-part series on .NET 2.0 configuration up on CodeProject.
Unraveling the mysteries of .NET 2.0 configuration
Decoding the mysteries of .NET 2.0 configuration
Cracking the mysteries of .NET 2.0 configuration
Highly recommended, well written and extremely helpful!
Marc
Here's the "Add existing item" dialog in VS 2008:
Click on the little dropdown indicator on the "Add" button and pick "Add as Link" from the context menu.
Marc
One design option is to avoid accessing the app.config directly from your class library projects altogether, thus avoiding the extra external dependency.
Rather, only your executable project knows about the config file and it can explicitly pass the appropriate config information to the libraries when it creates objects from them or initializes them.
I understand this is a old question but there is a much easier way of achieving this. If you are using Visual Studio 2008 or higher there is a Project type called "Shared Project".
A Shared Project can have pretty much anything that another types of Projects can contain. This is not only for C# but for all languages that VS2015 supports. When something is included in the Shared Project it is available to other projects after you add a reference to it (see below).
The major difference with Classes in a Shared Project VS a Shared Library is when you compile the program everything that is in the Shared Project will be Compiled directly into your project not as a separate file (.dll, .exe). Think of it like everything that is in the Shared Project is inserted into the other projects. Here is a small tutorial on setting this up and using it:
Visual Studio 2015 - Shared Project Tutorial:
Create the New Shared Project by selecting File->New->Project or Right Click on the Solution in the Solution Explorer and select Add->New Project. When the Dialog shows up select "Shared Project", give the Project a name TestShared in this example.
After the New Project is added you can add anything you need to be available to other projects. In this case we will add the app.config. Right Click on the Shared Project and select Add->New Item. Select Visual C#->Data->XML File naming it obviously to app.config.
Finally add a reference to the Shared Project by Right Clicking the Project that you need to share the project with and select Add->Reference. In the Reference Manager Dialog select your Shared Project, it will be listed under the "Shared Projects" item on the Left.
Now everything that is in the Shared Project is available in the other project, there is no need to do any using imports or anything like that. It simply works. This pattern is quite handy when you are developing a program and need to have several different GUI's (Windows, iOS, Android etc). For example you could have one shared project for the "Core" functionality and then have a separate GUI Project for each of the different Operating Systems you want to support in your program.
I realize that this is a older question but since this showed up in Google I thought I would answer this so when others are looking for the same thing they know about this very powerful VS feature.
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config = ConfigurationManager.OpenExeConfiguration(Path.Combine(#"D:\", "config.exe"));
foreach (string key in config.AppSettings.Settings.AllKeys)
{
string value = config.AppSettings.Settings[key].Value;
ConfigurationManager.AppSettings.Set(key, value);
}