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

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


当前回答

在我最终完成了关于公共字符串的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

其他回答

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

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

我也在找这个。我有一个运行HWC的项目,我想让网站远离应用程序树,但我不想让它在调试(或发布)目录。FWIW是公认的解决方案(这个也是),它只标识可执行文件所在的目录。

找到我一直在用的那个目录

string startupPath = System.IO.Path.GetFullPath(".\\").

我也遇到过类似的情况,在google搜索无果之后,我声明了一个公共字符串,它修改调试/发布路径的字符串值以获得项目路径。使用这种方法的一个好处是,因为它使用了当前项目的目录,所以不管你是从调试目录还是发布目录工作:

public string DirProject()
{
    string DirDebug = System.IO.Directory.GetCurrentDirectory();
    string DirProject = DirDebug;

    for (int counter_slash = 0; counter_slash < 4; counter_slash++)
    {
        DirProject = DirProject.Substring(0, DirProject.LastIndexOf(@"\"));
    }

    return DirProject;
}

然后你就可以在任何你想要的时候调用它,只使用一行:

string MyProjectDir = DirProject();

这在大多数情况下都是可行的。

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上传目录的代码

这个解决方案很适合我,在开发和测试和PROD服务器上使用ASP。NET MVC5通过c#:

var projectDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

如果你需要项目目录中的项目配置文件使用:

$(ProjectDir)