Better way to get the base directory?

前端 未结 9 1753
旧巷少年郎
旧巷少年郎 2020-12-25 13:59

I have this code to load a config file and read all the values and it works fine when running the application but of course fails on team city because the appdomain\'s base

相关标签:
9条回答
  • 2020-12-25 14:24

    how about:

    Application.StartupPath;
    
    0 讨论(0)
  • 2020-12-25 14:26

    differents ways to get the base directory

    1. AppDomain.CurrentDomain.BaseDirectory

    2. Directory.GetCurrentDirectory() // not guaranteed to work on Mobile application

    3. Environment.CurrentDirectory // this calls Directory.GetCurrentDirectory()

    4. this.GetType().Assembly.Location // Assembly.location

    5. Application.StartupPath // for windows forms apps

    6. Application.ExecutablePath // same as Application.StartupPath

    0 讨论(0)
  • 2020-12-25 14:26

    So it sounds/looks like you're attempting to obtain the configuration file for an assembly. The following should accomplish that task by accessing the 'Location' property of the assembly and using it to retrieve the configuration path:

    static string GetConfigFileByType(Type type)
    {
        Configuration config = 
            ConfigurationManager.OpenExeConfiguration(type.Assembly.Location);
    
        if (config.HasFile)
            return config.FilePath;
        throw new FileNotFoundException();
    }
    
    0 讨论(0)
提交回复
热议问题