Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create app config file if doesn't exist C#

When I try to open my app config file by

ConfigurationManager.OpenExeConfiguration(filePath);

it returns an exception, because there is no file. But I need to create this file in this case. But as I know, config file create by adding at VS like How to: Add an Application Configuration File to a C# Project

So, how to create this file in other way?

like image 596
Artem Kyba Avatar asked Dec 16 '13 15:12

Artem Kyba


People also ask

Can class library have app config?

Class libraries can access configuration settings in the same way as executable apps, however, the configuration settings must exist in the client app's App. config file. Even if you distribute an App. config file alongside your library's assembly file, the library code will not read the file.

Does app config get compiled into DLL?

If you don't want to expose values, make sure you have an app. config with deployment values (empty, 0, or something). The values WILL be compiled into the DLL as default values.

Can I delete app config?

If the app has a configuration profile, delete it. Go to Settings > General > Profiles or Profiles & Device Management,* then tap the app's configuration profile. Then tap Delete Profile.


2 Answers

If you really want to create an empty config file at runtime you can do something like this, but note that if the config file already exists this code will overwrite it:

System.Text.StringBuilder sb = new StringBuilder();
sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
sb.AppendLine("<configuration>");
sb.AppendLine("</configuration>");

string loc = Assembly.GetEntryAssembly().Location;
System.IO.File.WriteAllText(String.Concat(loc, ".config"), sb.ToString());
like image 97
Ed Gibbs Avatar answered Sep 22 '22 00:09

Ed Gibbs


Just go to App.config file properties and change Copy to Output Directory setting from Do not copy to Copy always (or Copy if newer). That will automatically create config file during project build.

like image 20
Sergey Berezovskiy Avatar answered Sep 21 '22 00:09

Sergey Berezovskiy