处理MVC库中的路径

时间:2017-10-28 17:57:28

标签: c# asp.net .net asp.net-mvc

我有一个MVC项目和一个用于保存和删除图像的类库。

我将存储在变量中的图像的路径作为相对路径 我在Save()和Delete()方法中引用的Content\images\

save方法按照我的想法工作,但是删除会抛出一个错误,因为它与窗口目录中的当前路径相关。

// Works fine
File.WriteAllBytes(Path.Combine(Settings.ImagesPath, filename), binaryData);

// Error saying it cannot find the path in the C:\windows\system32\folder
File.Delete(Path.Combine(Settings.ImagesPath, filename));

我希望能够在Settings.ImagesPath字符串中的相对路径和绝对路径之间切换,但我尝试过的每篇SO文章都适用于一种情况或另一种情况。将绝对路径或相对路径转换为处理它们的常用方法的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

您应该使用Server.MapPath方法生成该位置的路径,并在Path.Combine方法中使用该路径。

var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
System.IO.File.Delete(fullPath);

Server.MapPath方法返回与指定虚拟路径对应的物理文件路径。在这种情况下,Server.MapPath(Settings.ImagesPath)会将物理文件路径返回到您的应用根目录中的Content\images\

在保存文件时也应该这样做。

您还可以在尝试删除文件之前检查文件是否存在

var fullPath = Path.Combine(Server.MapPath(Settings.ImagesPath), filename);
if (System.IO.File.Exists(fullPath))
{
    System.IO.File.Delete(fullPath);
}

Server.MapPath需要一个相对路径。因此,如果Settings.ImagePath中有绝对值,则可以使用Path.IsPathRooted方法确定它是否为虚拟路径

var p = Path.Combine(Path.IsPathRooted(Settings.ImagesPath)
                            ? path : Server.MapPath(Settings.ImagesPath), name);

if (System.IO.File.Exists(p))
{
    System.IO.File.Delete(p);
}

使用虚拟路径时,请确保它以~开头。

Settings.ImagesPath =   @"~\Contents\Pictures";
相关问题