2017-10-28 70 views
0

我有一个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串但每文章中,我已经试过作品一个场景或其他相对和绝对路径之间进行切换。将绝对或相对路径转换为处理它们的一些常见方式的最佳方式是什么?

+0

“Settings.ImagesPath”中有什么值? – Shyju

+0

您可以尝试使用'Server.MapPath'从相关的路径获取绝对路径。你可以使用'Path.Combine'来添加文件名。 – Michael

+0

@Shyju Content \ images \是当前值 – user3953989

回答

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"; 
+0

如果Settings.ImagesPath也是绝对路径,这也可以吗? – user3953989

+0

编号Server.MapPath需要一个虚拟路径。您可以通过一些逻辑来检查它是绝对路径还是虚拟路径,并根据需要使用Server.MapPath – Shyju

+0

您可以将它添加到您的示例中吗? – user3953989