创建应用程序配置文件(如果不存在)C#

Art*_*yba 6 .net c# app-config configuration-files

当我尝试打开我的应用程序配置文件时

ConfigurationManager.OpenExeConfiguration(filePath);
Run Code Online (Sandbox Code Playgroud)

它返回一个异常,因为没有文件.但在这种情况下我需要创建此文件.但据我所知,配置文件是通过在VS中添加如何:将应用程序配置文件添加到C#项目来创建的

那么,如何以其他方式创建此文件?

Ed *_*bbs 13

如果你真的想在运行时创建一个空的配置文件,你可以这样做,但请注意,如果配置文件已经存在,这段代码将覆盖它:

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());
Run Code Online (Sandbox Code Playgroud)

  • “sb.toString()”应该是“sb.ToString()”,否则完美的答案。谢谢! (2认同)