而不是运行其路径硬编码的外部程序,我想获得当前的项目目录。我正在使用自定义任务中的进程调用外部程序。

我该怎么做呢?AppDomain.CurrentDomain.BaseDirectory只是给了我VS 2008的位置。


当前回答

using System;
using System.IO;

// Get the current directory and make it a DirectoryInfo object.
// Do not use Environment.CurrentDirectory, vistual studio 
// and visual studio code will return different result:
// Visual studio will return @"projectDir\bin\Release\netcoreapp2.0\", yet 
// vs code will return @"projectDir\"
var currentDirectory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);

// On windows, the current directory is the compiled binary sits,
// so string like @"bin\Release\netcoreapp2.0\" will follow the project directory. 
// Hense, the project directory is the great grand-father of the current directory.
string projectDirectory = currentDirectory.Parent.Parent.Parent.FullName;

其他回答

在我最终完成了关于公共字符串的us的第一个答案以获得答案后,我突然意识到您可能可以从注册表中读取一个值以获得您想要的结果。事实证明,这条路线甚至更短:

首先,你必须包括微软。Win32命名空间,这样你就可以使用注册表:

using Microsoft.Win32;    // required for reading and / or writing the registry

以下是主要代码:

RegistryKey Projects_Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\VisualStudio\9.0", false);
string DirProject = (string)Projects_Key.GetValue(@"DefaultNewProjectLocation");

关于这个答案需要注意:

我使用的是Visual Studio 2008专业版。如果您正在使用另一个版本,(即2003,2005,2010;等等),那么你可能必须修改子密钥字符串的'version'部分(即8.0,7.0;等等)。

如果你使用了我的答案之一,如果这不是一个过分的要求,那么我想知道你使用了我的方法,为什么。祝你好运。

dm

好吧,2021年,有点晚了…但我在许多项目中发现的所有可能性都让我很恼火:

bin /调试 bin / x86 -调试 bin /调试- net5 0-windows。 ...

来吧……我只需要一行程序(或几乎)来处理测试单元中的一些文件;我需要在所有过去、现在、(可能是未来)的项目中使用它。

因此,如果项目名称与它所在的相对文件夹相同:

使用程序集名称选择项目根文件夹名称; 回去找,直到找到那个名字。

代码示例:

string appName = Assembly.GetExecutingAssembly().GetName().Name;
var dir = new DirectoryInfo(Environment.CurrentDirectory);
while (dir.Name != appName) {
  dir = Directory.GetParent(dir.FullName);
}
return dir.FullName;

我使用以下解决方案来完成这项工作:

string projectDir =
    Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\.."));

使用这个来获得项目目录(为我工作):

string projectPath = 
    Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

Try:

var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);

这是不同于其他的解决方案,也考虑到可能的x86或x64构建。