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?
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.
This file is needed by your application as you need to access it. The best way is to add it with Visual Studio as you wrote it. You have to ensure that it is properly deployed on the target machine at setup.
Then if it is not present on disk at runtime, it's a good behaviour to crash. You can display a message to the user (catch the exception).
Why would you want to create it any other way? Is it to make sure you always have a config file, even if the user deletes it? And why would a user do that? Oh never mind.
If you want to make sure there's always a config file, you can create it yourself if it isn't there:
if (!File.Exists(configFilePath)) ...
Config files are just XML. So you could create a new file and populate it with default data, right before you want to read a key from it.
However one would expect a user not to delete a config file. Just sayin'.
来源:https://stackoverflow.com/questions/20614189/create-app-config-file-if-doesnt-exist-c-sharp