pwas pwas - 1 year ago 132
C# Question

File not found with file result

I have an action that serves the file:

public ActionResult() GetFile
return this.File("C:\\test.txt", "text/plain",

But action causes an error:

FileNotFoundException: Could not find file: C:\test.txt

I am sure that file exstis - it can be opened via "Run" window (Win + R).
Why core mvc doesn't "see" the file?

Answer Source

The File() overload that accepts a string, is defined as:

public virtual VirtualFileResult File(string virtualPath, string contentType)

As you can see, the name of the parameter is virtualPath. That means you have to pass a virtual path to the file, not a physical path.

(Virtual path means a path that is relative to the current application. For example: ~/Content/test.txt, where ~ denotes the application root directory.)

If you're insisting on serving a physical file that is above your application root, you can read it beforehand and pass the actual bytes to the corresponding File() overload:

var physicalFilePath = "C:\\test.txt";
var fileBytes = System.IO.File.ReadAllBytes(physicalFilePath);

return this.File(fileBytes, "text/plain", "test.txt");


Actually, the base controller does provide a PhysicalFile() method that can be used to serve a file using a physical path. In your case:

return PhysicalFile("C:\\test.txt", "text/plain", "test.txt");

You should also keep in mind that (usually) the process under which your application runs, won't have suffice permissions to read from the root of C:\.

See Source

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download