我有一个为文件提供服务的操作:
public ActionResult() GetFile
{
return this.File("C:\\test.txt", "text/plain",
"test.txt");
}
但是操作会导致错误:
FileNotFoundException: Could not find file: C:\test.txt Microsoft.AspNetCore.Mvc.Internal.VirtualFileResultExecutor+d__4.MoveNext()
我确定该文件存在 - 它可以通过“运行”窗口 (Win + R) 打开。 为什么 Asp.net core mvc 看不到文件?
最佳答案
接受 string
的 File()
重载定义为:
public virtual VirtualFileResult File(string virtualPath, string contentType)
如您所见,参数的名称是virtualPath
。这意味着您必须传递文件的虚拟路径,而不是物理路径。
(虚拟路径是指相对于当前应用程序的路径。例如:~/Content/test.txt
,其中~
表示应用程序根目录。 )
如果您坚持提供位于应用程序根目录之上的物理文件,您可以事先读取它并将实际字节传递给相应的 File()
重载:
var physicalFilePath = "C:\\test.txt";
var fileBytes = System.IO.File.ReadAllBytes(physicalFilePath);
return this.File(fileBytes, "text/plain", "test.txt");
更新:
实际上,基本 Controller 确实提供了一个PhysicalFile()
方法,可用于使用物理路径为文件提供服务。在你的情况下:
return PhysicalFile("C:\\test.txt", "text/plain", "test.txt");
您还应该记住,(通常)您的应用程序运行的进程没有足够的权限从 C:\
的根目录读取。
参见 Source
关于c# - 文件结果找不到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40702284/