2014-12-04 2 views
1

내 웹 사이트에서 사용자에게 파일 다운로드를 제공합니다. 파일이 존재하면 정상적으로 작동합니다.handling DirectoryNotFoundException errors

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

을하고, 사용자는 웹 사이트에 JSON 문자열을 참조하십시오 파일이 어떤 이유에서 제거 될 경우, 나는 Visual Studio에서 다음과 같은 오류가 발생합니다.

나는 스트림을이 제안을 사용

mediaFile.FilesystemLocation

var result = new HttpResponseMessage(HttpStatusCode.OK); 
result.Content = new StreamContent(
     new FileStream(mediaFile.FilesystemLocation, FileMode.Open)); 
는 단순히이 :

public virtual string FilesystemLocation 
{ 
    get { return Path.Combine(FilesystemRoot, Id + "." + Extension); } 
} 
내가 try/catch 블록에 모든 것을 넣어 시도했지만 그때는 모든 그것의 참조를 잃은

다른 클래스들에게.

제 질문은이 코드를 어떻게 처리하고이 오류를 방지 할 수 있습니까?

"파일을 찾을 수 없음, 관리자에게 문의하십시오"등과 같은 메시지를 사용자에게 표시하는 것이 이상적입니다.

감사합니다.

+0

'try/catch 블록에 모든 것을 넣는 것'으로 인해 참조가 손실되지 않아야합니다. –

답변

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

+3

하지만 여전히 당신은 try/catch 주위에 잡을 필요가있을 것입니다. Content = ..., 파일이 존재 체크와 오프닝 사이에 여전히있을 수 있습니다. – weloytty

+1

좋은 지적. 코드를 업데이트하겠습니다. –