首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >ASP.NET System.IO.File.Delete不是工作物理路径,但需要一条虚拟路径

ASP.NET System.IO.File.Delete不是工作物理路径,但需要一条虚拟路径
EN

Stack Overflow用户
提问于 2018-05-31 04:07:53
回答 2查看 342关注 0票数 -4

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

回答 2

Stack Overflow用户

回答已采纳

发布于 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.
}
票数 0
EN

Stack Overflow用户

发布于 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属性。

另外,当你遇到类似的问题时,捕捉异常并记录它也是非常有用的。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50612637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档