Create app config file if doesn't exist C#

2019-02-17 20:27发布

问题:

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?

回答1:

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());


回答2:

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.



回答3:

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).



回答4:

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'.