Handling FileContentResult when file is not found

In ASP.NET Core, use NotFound()

Your controller must inherit of Controller and the method must return ActionResult

Example:

public ActionResult GetFile(string path)
{
    if (!File.Exists(path))
    {
        return NotFound();
    }
    
    try
    {
        return new FileContentResult(File.ReadAllBytes(path), "application/octet-stream");
    }
    catch (FileNotFoundException)
    {
        return NotFound();
    }
}

Note: the above code doesn't handle all cases of file operations errors as invalid chars in path or file unavailability (because it is beyond the scope of the current answer) and proper responses (like restricted file access due to permissions or else)


The correct way to handle a not found in a web application is by returning a 404 HTTP status code to the client which in ASP.NET MVC terms translates into returning a HttpNotFoundResult from your controller action:

return new HttpNotFoundResult();

Ahh, oops, didn't notice you were still on ASP.NET MVC 2. You could implement it yourself because HttpNotFoundResult was introduced only in ASP.NET MVC 3:

public class HttpNotFoundResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        context.HttpContext.Response.StatusCode = 404;
    }
}