【问题标题】:Using a Relative Paths in C#在 C# 中使用相对路径
【发布时间】:2019-05-29 04:05:52
【问题描述】:

我正在尝试在我的数据库中植入一张图片。我可以使用绝对路径成功地做到这一点,但这不会作为永久解决方案。

 Image = File.ReadAllBytes(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg"),

我怎么能得到同样的路径如此解决。使用类似

~\Images\Ferrari488.jpg

任何帮助将不胜感激。

【问题讨论】:

  • 你看过Path.Combinestackoverflow.com/questions/5203945/…吗?
  • 哦,MVC 应用程序的好问题。 ~ 应该指向 wwwroot 但它没有? VS 突然决定使用IIS Express 目录而不是 Project 目录作为主路径,不是吗?尝试从Environment 打印WorkingDirectory 变量,它会告诉你发生了什么。

标签: c# asp.net-mvc


【解决方案1】:

要从路径中仅获取文件名,您可以使用Path.GetFileName('path');,在您的情况下,您可以先获取文件名:

var fileName = System.IO.Path.GetFileName(@"E:\Graded Unit\Implementation\YorkiesVehicleHire\YorkiesVehicleHire\Images\Ferrari488.jpg");
//filename will now only contain: Ferrari488.jpg

//Now let's concatenate it with ~/Images/
var storingPath= "~\Images\" + fileName;

现在对于绝对路径,请尝试使用Server.MapPath("~"),它将物理路径返回到应用程序的根目录。

所以在你的情况下,如果你想获得~\Images\Ferrari488.jpg 的绝对路径,那么它看起来像:Server.MapPath("~\Images\Ferrari488.jpg");System.Web.HttpContext.Current.Server.MapPath("~\Images\Ferrari488.jpg");

var absolutePath = System.Web.HttpContext.Current.Server.MapPath(storingPath);
Image = File.ReadAllBytes(absolutePath);

【讨论】:

  • 我仍然需要 File.ReadAllBytes,以便我可以将图像转换为字节以将其存储在数据库中。 Server.MapPath 会这样做吗?我无法让“服务器”解决任何想法 using 语句应该是什么?
  • 感谢您的回复,我现在可以正常使用了。我用过, var absolutePath = System.Web.HttpContext.Current.Server.MapPath(@"~\Images\");然后,Image = File.ReadAllBytes(absolutePath + "Ferrari488.jpg"),再次感谢您的帮助。
  • absolutePath + "Ferrari488.jpg" 不要那样做。使用Path.Combine
猜你喜欢
  • 1970-01-01
  • 2011-08-24
  • 2011-06-15
  • 1970-01-01
  • 1970-01-01
  • 2022-06-19
  • 1970-01-01
  • 2016-11-09
相关资源
最近更新 更多