how to determine whether app.config file exists

自作多情 提交于 2019-11-28 13:21:03

Most simple way that I can think of is to add some "dummy" application setting flag then check for that flag, e.g.:

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

The AppDomain reports on where it expects the configuration file for the application to reside. You can test if the file actually exists (with no need for dummy AppSettings, and no need to try and work out what the configuration file should be called, or where it is located):

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

You can create method in static class

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" )
    }
}

And then use where you want

ConfigurationManagerHelper.Exists();  // or pass assembly
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!