当我尝试通过以下方式打开我的应用程序配置文件时
ConfigurationManager.OpenExeConfiguration(filePath);
它返回一个异常,因为没有文件。但是在这种情况下我需要创建这个文件。但据我所知,配置文件是通过在 VS 中添加来创建的,例如 How to: Add an Application Configuration File to a C# Project
那么,如何用其他方式创建这个文件呢?
最佳答案
如果您真的想在运行时创建一个空的配置文件,您可以这样做,但请注意,如果配置文件已经存在,此代码将覆盖它 :
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());
关于c# - 如果不存在则创建应用程序配置文件 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20614189/