如果不存在,则创建应用程序配置文件 C# [英] Create app config file if doesn't exist C#

查看:46
本文介绍了如果不存在,则创建应用程序配置文件 C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过以下方式打开我的应用配置文件时

When I try to open my app config file by

ConfigurationManager.OpenExeConfiguration(filePath);

它返回一个异常,因为没有文件.但在这种情况下我需要创建这个文件.但据我所知,配置文件是通过在 VS 中添加创建的,例如 How to: Add an Application Configuration File to a C#项目

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

这篇关于如果不存在,则创建应用程序配置文件 C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆