如何确定app.config文件是否存在
有没有办法找出app.config文件是否存在,而不使用“File.Exists”? 我试过了
if ( !ConfigurationManager.ConnectionStrings.ElementInformation.IsPresent ) {...}
但即使存在连接字符串的app.config,IsPresent也是假的。
编辑:我是否误解了IsPresent属性?
我能想到的最简单的方法是添加一些“虚拟”应用程序设置标志,然后检查该标志,例如:
if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["dummyflag"])) { //config file doesn't exist.. }
AppDomain
报告它期望应用程序的配置文件驻留的位置。 您可以测试文件是否确实存在(不需要虚拟AppSettings,也不需要尝试找出应该调用的配置文件或它所在的位置):
public static bool CheckConfigFileIsPresent() { return File.Exists(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); }
您可以在静态类中创建方法
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