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

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


当前回答

string projPath = Path.GetFullPath(@"..\..\..\");
Console.WriteLine(projPath);

这对我来说一直都很有效。试一试。

其他回答

如果项目在IIS express上运行,则环境。CurrentDirectory可以指向IIS Express所在的位置(默认路径是C:\Program Files (x86)\IIS Express),而不是指向项目所在的位置。


这可能是各种项目最适合的目录路径。

AppDomain.CurrentDomain.BaseDirectory

这就是MSDN的定义。

获取程序集解析器用于探测程序集的基目录。

这还将通过从当前执行目录向上导航两级来为您提供项目目录(这不会为每次构建返回项目目录,但这是最常见的)。

System.IO.Path.GetFullPath(@"..\..\")

当然,您希望将其包含在某种验证/错误处理逻辑中。

另一种方法

string startupPath = System.IO.Directory.GetParent(@"./").FullName;

如果你想获取bin文件夹的路径

string startupPath = System.IO.Directory.GetParent(@"../").FullName;

也许有更好的方法=)

Try:

            {
                OpenFileDialog fd = new OpenFileDialog();
                fd.Multiselect = false;
                fd.Filter = "Image files (*.bmp, *.jpg)|*.bmp;*.jpg|All files (*.*)|*.*";
                if (fd.ShowDialog() == true)
                {
                    if (fd.CheckFileExists)
                    {
                        var fileNameToSave = GetTimestamp(DateTime.Now) + Path.GetExtension(fd.FileName);
                        var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
                        var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);
                        var imagePath = Path.Combine(directory + @"\Uploads\" + fileNameToSave);
                        File.Copy(fd.FileName, imagePath);

                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

这是上传图片到WPF上传目录的代码

(因为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 ?? "";
  }
}