处理DirectoryNotFoundException错误

问题描述:

我提供文件从我的网站下载到用户。当文件存在时,它工作正常。但是,如果该文件是无论出于何种原因删除,我得到以下错误在Visual Studio:处理DirectoryNotFoundException错误

An exception of type 'System.IO.DirectoryNotFoundException' occurred in 
mscorlib.dll but was not handled in user code 

和用户只是看到网站上的JSON字符串。

我用这个报价上涨流:

var result = new HttpResponseMessage(HttpStatusCode.OK); 
result.Content = new StreamContent(
     new FileStream(mediaFile.FilesystemLocation, FileMode.Open)); 

mediaFile.FilesystemLocation很简单:

public virtual string FilesystemLocation 
{ 
    get { return Path.Combine(FilesystemRoot, Id + "." + Extension); } 
} 

我试图把整个事情在try/catch块,但随后失去了所有它的引用到其他班级。

所以我的问题是,我如何处理这段代码并防止这个错误?

理想情况下,我只想向用户显示一条消息,“找不到文件,请联系您的管理员”或类似的东西。

谢谢!

+0

'把整个事情放在try/catch块'不应该导致任何引用丢失。 – 2014-12-04 17:33:08

System.IO.File.Exists将在这里成为你的朋友。在您设置result.Content之前,请先调用它。如果文件不存在,该方法将返回false,您可以相应地调整您的逻辑。

var filepath = mediaFile.FilesystemLocation; 

if (!File.Exists(filepath)) 
{ 
    return new HttpResponseMessage(404); 
} 
else{ 
    var result = new HttpResponseMessage(HttpStatusCode.OK); 

    //just in case file has disappeared/or is locked for open, 
    //wrap in try/catch 
    try 
    { 
     result.Content = new StreamContent(
      new FileStream(filepath, FileMode.Open)); 
    } 
    catch 
    { 
     return new HttpResponseMessage(500);   
    } 

    return result; 
} 
+1

哇,那很美。谢谢,我会试试看。 – SkyeBoniwell 2014-12-04 17:42:04

+3

,但仍然需要尝试/抓住result.Content = ...,因为您仍然可以在检查存在并打开文件之间移除该文件。 – weloytty 2014-12-04 17:44:53

+1

好点。我会更新代码。 – 2014-12-04 17:46:36