SkyeBoniwell
SkyeBoniwell

Reputation: 7112

handling DirectoryNotFoundException errors

I offer up file downloads from my website to users. When the file exists, it works fine. But if the file is removed for whatever reason, I get the following error in Visual Studio:

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

and the users just see a JSON string on the website.

I use this offer up a stream:

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

mediaFile.FilesystemLocation is simply this:

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

I tried putting the whole thing in a try/catch block but then it lost all it's references to other classes.

So my question is, how can I handle this code and prevent this error?

Ideally, I'd just like to display a message to the user, "File Not Found, please contact your Administrator" or something like that.

Thanks!

Upvotes: 1

Views: 1319

Answers (1)

Philip Pittle
Philip Pittle

Reputation: 12305

System.IO.File.Exists is going to be your friend here. Before you set result.Content call this first. If the file doesn't exist, the method will return false and you can adjust your logic accordingly.

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

Upvotes: 2

Related Questions