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

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


当前回答

试试这个,很简单

HttpContext.Current.Server.MapPath("~/FolderName/");

其他回答

您可以尝试这两种方法中的一种。

string startupPath = System.IO.Directory.GetCurrentDirectory();

string startupPath = Environment.CurrentDirectory;

告诉我,你觉得哪个更好

如果你想知道你的解决方案所在的目录是什么,你需要这样做:

 var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
            if (parent != null)
            {
                var directoryInfo = parent.Parent;
                string startDirectory = null;
                if (directoryInfo != null)
                {
                    startDirectory = directoryInfo.FullName;
                }
                if (startDirectory != null)
                { /*Do whatever you want "startDirectory" variable*/}
            }

如果你只使用getcurrentdirectory()方法,无论你是在调试还是发布,你都会得到构建文件夹。希望这对你有所帮助!如果你忘记了验证,它会是这样的:

var startDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;

(因为22个答案是不够的……这里还有一个....)

Mike Nakis给出了一个很好的答案,我在上面添加了一些改进。这只是对他的漂亮代码稍加修饰的版本。

正如Mike指出的,这个类文件必须在项目的根目录中。

下面的内容我没有遇到任何问题,但可能有我没有意识到的细微差别。YMMV。

using System.IO;
using System.Runtime.CompilerServices;

namespace Whatever
{
  internal static class ProjectPathInfo
  {
    public static string CSharpClassFileName = nameof(ProjectPathInfo) + ".cs";
    public static string CSharpClassPath;
    public static string ProjectPath;
    public static string SolutionPath;

    static ProjectPathInfo() {
      CSharpClassPath = GetSourceFilePathName();
      ProjectPath = Directory.GetParent(CSharpClassPath)!.FullName;
      SolutionPath = Directory.GetParent(ProjectPath)!.FullName;
    }

    private static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null ) => callerFilePath ?? "";
  }
}

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

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

好吧,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;