Create app config file if doesn't exist C#

左心房为你撑大大i 提交于 2019-12-01 04:40:38

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!