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

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


当前回答

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

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

string startupPath = Environment.CurrentDirectory;

告诉我,你觉得哪个更好

其他回答

.Parent.Parent.Parent.Parent.FullName Directory.GetParent (Directory.GetCurrentDirectory ())

会给你项目目录。

试试这个,很简单

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

我没有看到使用字符串的解决方案。连接和字符串。Split + SkipLast 4个元素,在这里。

            string projectDir = 
            string.Join('/', AppDomain.CurrentDomain.BaseDirectory
                .Split(new char[] { '/' })
                .SkipLast(4));

获取c#项目根文件夹的正确方法是利用[CallerFilePath]属性获取源文件的完整路径名,然后减去文件名加扩展名,留下项目的路径。

下面是如何做到这一点:

在项目的根文件夹中,添加包含以下内容的ProjectSourcePath.cs文件:

internal static class ProjectSourcePath
{
    private const  string  myRelativePath = nameof(ProjectSourcePath) + ".cs";
    private static string? lazyValue;
    public  static string  Value => lazyValue ??= calculatePath();

    private static string calculatePath()
    {
        string pathName = GetSourceFilePathName();
        Assert( pathName.EndsWith( myRelativePath, StringComparison.Ordinal ) );
        return pathName.Substring( 0, pathName.Length - myRelativePath.Length );
    }
}

字符串?需要一个非常晚的c#版本#nullable enable;如果你没有,那就去掉?。

Assert()函数是我自己的;如果你喜欢过危险的生活,你可以用你自己的代替它,或者省略它。

函数GetSourceFilePathName()的定义如下:

using System.Runtime.CompilerServices

    public static string GetSourceFilePathName( [CallerFilePath] string? callerFilePath = null ) //
        => callerFilePath ?? "";

一旦你有了以上这些,你可以这样使用它:

string projectSourcePath = ProjectSourcePath.Value;

1 'proper'在:万无一失的;可靠;没有假设;不牢靠的:不牢靠的;不一定在某些项目上成功,但在另一些项目上失败;当你改变不相关的东西时,不太可能毫无征兆地坏掉;等。

如果你真的想确保你得到源项目目录,不管bin输出路径设置为什么:

添加一个预构建事件命令行(Visual Studio:项目属性->构建事件): echo $(MSBuildProjectDirectory) > $(MSBuildProjectDirectory)\Resources\ProjectDirectory.txt 将ProjectDirectory.txt文件添加到资源。resx项目(如果它还不存在,右键单击项目->添加新项目->资源文件) 使用Resources.ProjectDirectory从代码中访问。