【问题标题】:Check whether the app.config file exists or not in console app C# [duplicate]检查控制台应用程序C#中是否存在app.config文件[重复]
【发布时间】:2013-03-15 19:24:00
【问题描述】:

我在 C# 中创建了一个控制台应用程序。我想在我的项目中使用app.config 文件。

我的问题是:在阅读app.config 之前,我想确保app.config 存在。如何检查?

请帮帮我!谢谢大家

【问题讨论】:

标签: c# console app-config


【解决方案1】:

虽然您可以简单地使用if( File.Exists( Assembly.GetEntryAssembly().Location + ".config" ) ),但它有点老套和脆弱,并且如果配置文件位于另一个目录中则不起作用。

我认为最好的方法是尝试显式加载配置并捕获异常(因为缺少 .ConfigurationExists 属性),如下所示:

try {
    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
} catch(ConfigurationErrorsException) {
    return false;
}

【讨论】:

    【解决方案2】:

    在 app.config 属性的 get 和 set 方法中(或者如果您有多个属性),您可以首先通过调用 File.Exists(path) 来确定文件是否存在。如果没有,您可以根据需要抛出异常。

    http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.85).aspx

    【讨论】:

      猜你喜欢
      • 2012-04-21
      • 2022-11-11
      • 2012-03-21
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2011-10-25
      相关资源
      最近更新 更多