System.IO.File.Exists始终返回true

时间:2014-09-21 13:12:06

标签: c# asp.net

我正在尝试检查服务器上是否存在文件&如果文件存在则警告使用,以便他可以重命名文件&再次上传。但即使我将!添加到System.IO.File.Exists

,我的代码也会返回true

此代码适用于ASP.net webform应用程序

string filename = Path.GetFileName(FileUploadControl.FileName);
if (System.IO.File.Exists("../pdf/news/" + FileUploadControl.FileName))
{
    ViewState["_fileName"] = null;
    StatusLabel.Text = "File with this name already exsists, Please rename file and Upload gain";
}
else
{
    FileUploadControl.SaveAs(Server.MapPath("../pdf/news/") + filename);
    StatusLabel.Text = "Upload status: File uploaded!";
    //_fileName = FileUploadControl.FileName;
    ViewState["_fileName"] = FileUploadControl.FileName;
}

我确信我做错了但却无法弄清楚是什么。

2 个答案:

答案 0 :(得分:5)

此处最可能的问题是您在存在检查之前未使用Server.MapPath。在哪里看?我们不知道。但是因为你打算以后再这样做:早点移动它:

var path = Path.Combine(Server.MapPath("../pdf/news/"), filename);

并使用path 存在检查和最终创建。

请注意,编辑网络应用树中的文件不是一个好主意:

  • 它可以触发应用程序池重启
  • 这是一个潜在的黑客攻击 - 矢量
  • 它不会缩放到群集

答案 1 :(得分:1)

我认为问题是你没有在支票中映射路径。

if (System.IO.File.Exists(Server.MapPath("../pdf/news/" + FileUploadControl.FileName)))
{
相关问题