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?
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.
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.
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.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With