在C#中使用相对路径

时间:2019-05-29 04:05:52

标签: c# asp.net-mvc

我正在尝试用图像为数据库播种。我可以使用绝对路径成功完成此操作,但是这不能作为永久解决方案。

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

如何获得相同的路径,以便解决。使用类似

~\Images\Ferrari488.jpg

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分: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");

OR

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