Reputation: 3373
I have an action that serves the file:
public ActionResult() GetFile
{
return this.File("C:\\test.txt", "text/plain",
"test.txt");
}
But action causes an error:
FileNotFoundException: Could not find file: C:\test.txt Microsoft.AspNetCore.Mvc.Internal.VirtualFileResultExecutor+d__4.MoveNext()
I am sure that file exstis - it can be opened via "Run" window (Win + R). Why Asp.net core mvc doesn't "see" the file?
Upvotes: 3
Views: 4216
Reputation: 49095
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");
Update:
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
Upvotes: 12