【问题标题】:ASP.NET System.IO.File.Delete not working - physical path, but a virtual path was expectedASP.NET System.IO.File.Delete 不起作用 - 物理路径,但需要虚拟路径
【发布时间】:2018-05-30 20:07:53
【问题描述】:

我正在尝试通过 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.

【问题讨论】:

  • 您确定文件路径正确吗? "C:/www/project/Images/" + landingCells.imageBytes 好像错了。
  • 不要吞下异常。你得到了什么例外?
  • 不要用MapPath指定完整路径
  • 可能正在使用中,请检查您是否正确处理元素等。异常消息并非微不足道!
  • 这是一个字符串,顺便说一句landingCells.imageBytes,从命名约定看来是字节数组什么的?

标签: asp.net asp.net-mvc


【解决方案1】:

我们使用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.
}

【讨论】:

    【解决方案2】:

    首先非常冒险的方法是硬编码文件夹的路径。如果管理员将应用程序移至 D 盘怎么办?

    恕我直言,问题在这里: var filePath = System.Web.HttpContext.Current.Server.MapPath("C:/www/project/Images/" + landingCells.imageBytes);

    您正在尝试访问一个流,所以路径很长,看起来或多或少像“C:\www\project\Images\0x00a00efe......”(所以这里的路很长)。您应该使用文件名而不是 imageBytes 属性。

    此外,当您遇到类似问题时,捕获异常并记录它非常有用。

    【讨论】:

    • 我知道这个名字是 imageBytes,但它实际上是一个文件名字符串:ANW00012018053015551423458244a89b23-5ed7-42a3-a2fc-4b15a90fb3cf.jpg,所以我使用的是文件名
    • 什么是异常(堆栈跟踪)?你能抓住它并在这里发布更多细节吗?
    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多