How to find path of active app.config file?

后端 未结 8 2012
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 04:43

I\'m trying to finish this exception handler:

if (ConfigurationManager.ConnectionStrings[\"ConnectionString\"]==null)
{
    string pathOfActiveConfigFile = .         


        
相关标签:
8条回答
  • 2020-12-02 05:18

    If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.

    When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.

    To get the location of the assembly you're running, try

    System.Reflection.Assembly.GetExecutingAssembly().Location
    
    0 讨论(0)
  • 2020-12-02 05:20

    Strictly speaking, there is no single configuration file. Excluding ASP.NET1 there can be three configuration files using the inbuilt (System.Configuration) support. In addition to the machine config: app.exe.config, user roaming, and user local.

    To get the "global" configuration (exe.config):

    ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
                        .FilePath
    

    Use different ConfigurationUserLevel values for per-use roaming and non-roaming configuration files.


    1 Which has a completely different model where the content of a child folders (IIS-virtual or file system) web.config can (depending on the setting) add to or override the parent's web.config.

    0 讨论(0)
  • 2020-12-02 05:30

    The first time I realized that the Unit testing project referenced the app.config in that project rather then the app.config associated with my production code project (off course, DOH) I just added a line in the Post Build Event of the Prod project that will copy the app.config to the bin folder of the test project.

    Problem solved

    I haven't noticed any weird side effects so far, but I am not sure that this is the right solution, but at least it seems to work.

    0 讨论(0)
  • 2020-12-02 05:31

    One more option that I saw is missing here:

    const string APP_CONFIG_FILE = "APP_CONFIG_FILE";
    string defaultSysConfigFilePath = (string)AppDomain.CurrentDomain.GetData(APP_CONFIG_FILE);
    
    0 讨论(0)
  • 2020-12-02 05:35

    Make sure you click the properties on the file and set it to "copy always" or it will not be in the Debug\ folder with your happy lil dll's to configure where it needs to be and add more cowbell

    0 讨论(0)
  • 2020-12-02 05:35

    Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location might do what you need.

    0 讨论(0)
提交回复
热议问题