获取基目录的更好方法是什么?
我有这个代码加载配置文件并读取所有值,它在运行应用程序时工作正常但当然在团队城市失败,因为appdomain的基本目录是构建脚本(psake)的启动位置。 我知道我可以在执行测试之前将目录更改为build dir,但我认为最好不管是什么时候加载配置文件都能正常工作。
XDocument.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, cfgFile));
有没有另一种方法可以让“BaseDirectory”真正起作用? 我也尝试了以下相同的结果:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase); XDocument.Load(Path.Combine(path, cfgFile));
编辑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; } }
正如您所看到的,我注释掉了目录的更改,这使得BaseDirectory成为构建文件/解决方案的位置而不是构建目录,无论我如何尝试访问它。 如果你问我,有点令人困惑。
更新我真的很想知道是否有可能获得程序集的目录,无论启动应用程序域的应用程序位于何种目录中。 怎么样?
string origAssemblyLocation = Assembly.GetExecutingAssembly().CodeBase;
每个MSDN:
Assembly.CodeBase属性
获取最初指定的程序集的位置
不同的方法来获取基目录
-
AppDomain.CurrentDomain.BaseDirectory
-
Directory.GetCurrentDirectory()
//不保证可以在Mobile应用程序上运行 -
Environment.CurrentDirectory
//这会调用Directory.GetCurrentDirectory()
-
this.GetType().Assembly.Location
// Assembly.location -
Application.StartupPath
//用于windows表单应用程序 -
Application.ExecutablePath
//与Application.StartupPath
相同
所以听起来/看起来你正在尝试获取程序集的配置文件。 以下应通过访问程序集的“Location”属性并使用它来检索配置路径来完成该任务:
static string GetConfigFileByType(Type type) { Configuration config = ConfigurationManager.OpenExeConfiguration(type.Assembly.Location); if (config.HasFile) return config.FilePath; throw new FileNotFoundException(); }
你的问题有点不清楚。 我真的不知道这是不是你想要的。
我通常使用AppDomain.CurrentDomain.BaseDirectory
备择方案
-
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
-
Environment.CurrentDirectory
试试这个:
Module[] modules = Assembly.GetExecutingAssembly().GetModules(); return Path.GetDirectoryName(modules[0].FullyQualifiedName);
你试过获取当前进程’ MainModule的FileName吗?
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName
还是GetEntryAssembly ()?
System.Reflection.Assembly.GetEntryAssembly().Location
我喜欢让我的类可配置 – 例如,他们在其构造函数中将文件夹名称作为参数。 这使得可以使用不同的配置文件进行测试。
在测试代码中我们使用:
TestContext.TestDeploymentDir
这是testrun文件夹,其中测试运行的所有程序集与测试部署项一起被复制到其中。 我们将我们的unit testing配置文件部署到测试运行文件夹 – 这可以在visual studio的testrunconfig对话框中指定。
对于我们的生产代码,我们通过
Assembly.GetExecutingAssembly().Location
构造函数,对我们有用。
怎么样:
Application.StartupPath;
string baseDirectory=Application.StartupPath.Split(Path.DirectorySeparatorChar)[0];
应用程序启动路径将返回保存exe的路径,我们将使用“\”拆分它,并将基目录作为“C:”,例如,