【问题标题】:how to determine whether app.config file exists如何判断app.config文件是否存在
【发布时间】:2011-07-14 21:46:15
【问题描述】:

有没有办法在不使用“File.Exists”的情况下找出 app.config 文件是否存在? 我试过了

if ( !ConfigurationManager.ConnectionStrings.ElementInformation.IsPresent )
{...}

但即使存在带有连接字符串的 app.config,IsPresent 也是 false。

编辑: 我是否误解了 IsPresent 属性?

【问题讨论】:

  • File.Exist 有什么问题?
  • 使用类似“ConfigurationManager.IsPresent”而不是“System.IO.File.Exists(System.Reflection.Assembly.GetEntryAssembly().Location + “.config”的代码会更简洁)"

标签: c# app-config


【解决方案1】:

AppDomain 报告它期望应用程序的配置文件驻留的位置。您可以测试该文件是否确实存在(不需要虚拟 AppSettings,也无需尝试找出应该调用的配置文件或它的位置):

public static bool CheckConfigFileIsPresent()
{
   return File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}

【讨论】:

  • 似乎有效,而且比接受的答案更干净,恕我直言,谢谢。
【解决方案2】:

你可以在静态类中创建方法

public static class ConfigurationManagerHelper
{
    public static bool Exists()
    {
        return Exists(System.Reflection.Assembly.GetEntryAssembly());
    }

    public static bool Exists(Assembly assembly)
    {
        return System.IO.File.Exists(assembly.Location + ".config" )
    }
}

然后在你想要的地方使用

ConfigurationManagerHelper.Exists();  // or pass assembly

【讨论】:

  • 当入口点不受管理时,这将失败,例如在单元测试中。
【解决方案3】:

我能想到的最简单的方法是添加一些“虚拟”应用程序设置标志,然后检查该标志,例如:

if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["dummyflag"]))
{
  //config file doesn't exist..
}

【讨论】:

  • 谢谢,这对我有用。你知道 IsPresent 的用途吗?
  • @ibr 干杯,很高兴它起作用了!抱歉,我第一次看到该属性时,文档中唯一提到的就是 Gets a value indicating whether the associated ConfigurationElement object is in the configuration file - 不知道为什么它为 ConnectionStrings 返回 false。
  • 与其设置“虚拟”标志,不如直接通过索引检查,例如ConfigurationManager.AppSettings[0])
  • @gvee 在写答案时没有想到这一点,但你明白了……会调查它并在需要时更新答案。
  • @gvee - 如果文件不存在并且您通过索引进行检查,您将收到 ArgumentOutOfRangeException。
猜你喜欢
  • 2015-11-15
  • 1970-01-01
  • 1970-01-01
  • 2010-12-11
  • 2013-05-12
  • 2010-09-17
  • 2021-07-26
  • 2013-10-31
  • 1970-01-01
相关资源
最近更新 更多