而不是运行其路径硬编码的外部程序,我想获得当前的项目目录。我正在使用自定义任务中的进程调用外部程序。
我该怎么做呢?AppDomain.CurrentDomain.BaseDirectory只是给了我VS 2008的位置。
而不是运行其路径硬编码的外部程序,我想获得当前的项目目录。我正在使用自定义任务中的进程调用外部程序。
我该怎么做呢?AppDomain.CurrentDomain.BaseDirectory只是给了我VS 2008的位置。
当前回答
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上传目录的代码
其他回答
基于guucu112的答案,但是对于。net核心控制台/窗口应用程序,它应该是:
string projectDir =
Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"..\..\.."));
我在一个xUnit项目中使用这个。net核心窗口应用程序。
您可以尝试这两种方法中的一种。
string startupPath = System.IO.Directory.GetCurrentDirectory();
string startupPath = Environment.CurrentDirectory;
告诉我,你觉得哪个更好
.Parent.Parent.Parent.Parent.FullName Directory.GetParent (Directory.GetCurrentDirectory ())
会给你项目目录。
我也遇到过类似的情况,在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();
这在大多数情况下都是可行的。
还有另一个不完美的解决方案(但可能比其他一些更接近完美):
protected static string GetSolutionFSPath() {
return System.IO.Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName;
}
protected static string GetProjectFSPath() {
return String.Format("{0}\\{1}", GetSolutionFSPath(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);
}
这个版本将返回当前项目的文件夹,即使当前项目不是解决方案的启动项目。
第一个缺陷是我跳过了所有的错误检查。这很容易解决,但只有当你将项目存储在驱动器的根目录中或在路径中使用连接(并且该连接是解决方案文件夹的后代)时才会成为问题,所以这种情况不太可能发生。我不完全确定Visual Studio是否能够处理这两种设置。
您可能遇到的另一个(更可能的)问题是,项目名称必须与项目的文件夹名称匹配才能找到它。
您可能遇到的另一个问题是项目必须在解决方案文件夹中。这通常不是问题,但如果您使用“将现有项目添加到解决方案”选项将项目添加到解决方案中,那么这可能不是解决方案的组织方式。
最后,如果您的应用程序将修改工作目录,您应该在修改之前存储这个值,因为这个值是相对于当前工作目录确定的。
当然,这也意味着您不能在项目属性对话框中更改项目的“构建->输出路径”或“调试->工作目录”选项的默认值。