处理MVC库中的路径
我有一个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
串但每文章中,我已经试过作品一个场景或其他相对和绝对路径之间进行切换。将绝对或相对路径转换为处理它们的一些常见方式的最佳方式是什么?
您应该使用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";
如果Settings.ImagesPath也是绝对路径,这也可以吗? – user3953989
编号Server.MapPath需要一个虚拟路径。您可以通过一些逻辑来检查它是绝对路径还是虚拟路径,并根据需要使用Server.MapPath – Shyju
您可以将它添加到您的示例中吗? – user3953989
“Settings.ImagesPath”中有什么值? – Shyju
您可以尝试使用'Server.MapPath'从相关的路径获取绝对路径。你可以使用'Path.Combine'来添加文件名。 – Michael
@Shyju Content \ images \是当前值 – user3953989