我正在尝试通过ASP.NET从服务器上删除文件。我正在尝试使用System.IO.File.Delete,如下所示:
try
{
var filePath = System.Web.HttpContext.Current.Server.MapPath("C:/www/project/Images/" + landingCells.imageBytes);
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}
catch
{
return false;
}
但每次它返回false时,我都可以向服务器写入一个文件:
try
{
System.IO.File.WriteAllBytes("C:/www/project/Images/" + filePath, bytes);
}
catch
{
return false;
}
但我无法删除该文件,是的文件路径和名称是正确的文件夹有完全控制,我做错了什么?
这是我得到的错误:
An error occured: ‘C:/www/project/Images/ANW00012018053015551423458244a89b23-5ed7-42a3-a2fc-4b15a90fb3cf.jpg' is a physical path, but a virtual path was expected.
发布于 2018-05-31 06:58:50
我们使用Server.MapPath
的原因是我们不想在代码中硬编码文件路径。
try
{
string fileName = "Sample.jpg";
var filePath = Server.MapPath("~/Images/" + fileName); // Do not pass byte array here
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
}
catch
{
// Do not swallow the exception. Instead, log them to persistant storage.
}
发布于 2018-05-31 04:21:59
首先,非常危险的方法是硬编码文件夹的路径。如果管理员将应用程序移动到磁盘D怎么办?
我的问题在这里:var filePath = System.Web.HttpContext.Current.Server.MapPath("C:/www/project/Images/" + landingCells.imageBytes);
你正在尝试访问一个流,所以路径很长,看起来或多或少像"C:\www\project\Images\0x00a00efe............."(so,这里的路径很长)。应该使用文件名而不是imageBytes
属性。
另外,当你遇到类似的问题时,捕捉异常并记录它也是非常有用的。
https://stackoverflow.com/questions/50612637
复制相似问题