how to determine whether app.config file exists

2020-02-06 21:17发布

Is there a way to find out whether an app.config file exists, without using "File.Exists"? I tried

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

but IsPresent is false even if app.config with a connection string exists.

Edit: Did I misinterpret the IsPresent Property?

标签: c# app-config
3条回答
Lonely孤独者°
2楼-- · 2020-02-06 22:01

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
查看更多
唯我独甜
3楼-- · 2020-02-06 22:02

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..
}
查看更多
▲ chillily
4楼-- · 2020-02-06 22:05

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);
}
查看更多
登录 后发表回答