而不是运行其路径硬编码的外部程序,我想获得当前的项目目录。我正在使用自定义任务中的进程调用外部程序。
我该怎么做呢?AppDomain.CurrentDomain.BaseDirectory只是给了我VS 2008的位置。
而不是运行其路径硬编码的外部程序,我想获得当前的项目目录。我正在使用自定义任务中的进程调用外部程序。
我该怎么做呢?AppDomain.CurrentDomain.BaseDirectory只是给了我VS 2008的位置。
当前回答
Try:
var pathRegex = new Regex(@"\\bin(\\x86|\\x64)?\\(Debug|Release)$", RegexOptions.Compiled);
var directory = pathRegex.Replace(Directory.GetCurrentDirectory(), String.Empty);
这是不同于其他的解决方案,也考虑到可能的x86或x64构建。
其他回答
我也在找这个。我有一个运行HWC的项目,我想让网站远离应用程序树,但我不想让它在调试(或发布)目录。FWIW是公认的解决方案(这个也是),它只标识可执行文件所在的目录。
找到我一直在用的那个目录
string startupPath = System.IO.Path.GetFullPath(".\\").
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 ?? "";
}
}
.Parent.Parent.Parent.Parent.FullName Directory.GetParent (Directory.GetCurrentDirectory ())
会给你项目目录。
基于guucu112的答案,但是对于。net核心控制台/窗口应用程序,它应该是:
string projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));
我在一个xUnit项目中使用这个。net核心窗口应用程序。