2014-09-21 151 views
-1

我试图检查服务器上是否存在文件&如果文件存在,警告使用,以便他可以重命名文件&再次上传。但即使我添加!System.IO.File.ExistsSystem.IO.File.Exists总是返回true

此代码我的代码总是返回true是ASP.net Web窗体应用程序

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; 
} 

我相信我做错了什么,但无法弄清楚什么。

+0

重复的问题。请阅读http://stackoverflow.com/questions/19592187/c-sharp-file-exists-returns-true-on-inexistent-file。如果它返回true,则表示它确实存在。编辑:链接的问题是一个更新http://stackoverflow.com/questions/4308421/file-exists-returning-true-for-a-file-that-doesnt-exist – 2014-09-21 13:15:32

+0

@RyanAlexander什么?不存在?我不这么认为... – DonBoitnott 2014-09-21 13:17:35

+0

抱歉打字。编辑。 – 2014-09-21 13:18:54

回答

5

这里最可能的问题是您在存在检查之前没有使用Server.MapPath。它在哪里看?我们不知道。但既然你打算这样做后:早期移动它:

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

而且使用path的存在检查,并最终创作。

请注意,修改Web应用程序树中的文件是一个坏主意:

  • 它可以触发一个应用程序池重启
  • 这是一个潜在的黑客攻击向量
  • 它不规模集群
+0

谢谢,这解决了这个问题...... – Learning 2014-09-21 13:26:28

+0

你已经提到了一些非常重要的问题'请注意,编辑你的Web应用程序树内的文件是一个坏主意' 。你能告诉我应该采取什么方法来解决你提到的问题。这对其他用户也有很大的帮助。我也会尝试寻找最好的方法。但是从你身边或参考文章的指针会很好。 – Learning 2014-09-22 03:39:44

+1

存储他们*在别处*;任何文档归档都可以这样做 - 可以像在您的Web树之外的文件树一样简单,或者它可以是NAS/SAN上的共享,或者它可以是CDN,或者它可以是RDBMS或NOSQL商店。有很多选择。 – 2014-09-22 09:07:21

1

我认为问题是你没有映射检查路径。

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