获取基目录的更好方法是什么?

mhe*_*xon 19 .net c#

我有这个代码加载配置文件并读取所有值,它在运行应用程序时工作正常但当然在团队城市失败,因为appdomain的基本目录是构建脚本(psake)启动的地方.我知道我可以在执行测试之前将目录更改为build dir,但我认为最好不管是什么时候加载配置文件都能正常工作.

XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cfgFile));
Run Code Online (Sandbox Code Playgroud)

有没有另一种方法可以让"BaseDirectory"真正起作用?我也尝试了以下相同的结果:

string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
XDocument.Load(Path.Combine(path, cfgFile));
Run Code Online (Sandbox Code Playgroud)

编辑1问题如下.我的解决方案基目录是"C:\ Project",所有编译的文件都复制到"C:\ Project\build".现在在psake构建脚本中,我有以下代码:

task Test -depends PrepareTests {
    try { 
        #$old = pwd
        #cd $build_dir
        &$mspec $mspec_projects --teamcity
        #cd $old
    }
    catch {
        &echo "Error starting test runner"
        Exit 1;
    }      
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我注释掉了目录的更改,这使得BaseDirectory成为构建文件/解决方案的位置而不是构建目录,无论我如何尝试访问它.如果你问我,有点令人困惑.

更新我真的很想知道是否有可能获得程序集的目录,无论启动应用程序域的应用程序位于什么目录中.怎么样?

Bam*_*aly 20

不同的方法来获取基目录

  1. AppDomain.CurrentDomain.BaseDirectory

  2. Directory.GetCurrentDirectory() //不保证可以在移动应用程序上工作

  3. Environment.CurrentDirectory //这个电话 Directory.GetCurrentDirectory()

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

  5. Application.StartupPath //用于Windows窗体应用

  6. Application.ExecutablePath // 与...一样 Application.StartupPath


jga*_*fin 10

你的问题有点不清楚.我真的不知道这是不是你想要的.

我通常使用 AppDomain.CurrentDomain.BaseDirectory

备择方案

  • Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
  • Environment.CurrentDirectory


csh*_*net 8

所以听起来/看起来你正在尝试获取程序集的配置文件.以下应通过访问程序集的"Location"属性并使用它来检索配置路径来完成该任务:

static string GetConfigFileByType(Type type)
{
    Configuration config = 
        ConfigurationManager.OpenExeConfiguration(type.Assembly.Location);

    if (config.HasFile)
        return config.FilePath;
    throw new FileNotFoundException();
}
Run Code Online (Sandbox Code Playgroud)


hem*_*emp 8

string origAssemblyLocation = Assembly.GetExecutingAssembly().CodeBase;
Run Code Online (Sandbox Code Playgroud)

每个MSDN:

Assembly.CodeBase属性

获取最初指定的程序集的位置

  • 要注意,这给出了一个uri类型的字符串,即file:///foo/bar/baz.DLL (2认同)