2014-12-04 176 views
1

我提供文件從我的網站下載到用戶。當文件存在時,它工作正常。但是,如果該文件是無論出於何種原因刪除,我得到以下錯誤在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

回答

2

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