c# - 文件结果找不到文件

标签 c# asp.net-core

我有一个为文件提供服务的操作:

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 看不到文件?

最佳答案

接受 stringFile() 重载定义为:

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/

相关文章:

asp.net - 在没有 IIS 和 VS 2017 的情况下使用 Kestrel

c# - ASP.NET Core 2.x 中间件的自定义依赖注入(inject)解析器?

c# - javascript 和 c# 中的传递参数问题

c# - 在 .net 核心 webapi Controller 中接受 byte[]

c# - 获取 .net 应用程序的事件窗口

c# - 什么是 Asp.Net Core TagHelper 等同于带脚本的 Html.ActionLink

asp.net-core - 缺少配置和管理 IIS Express 的组件

.net - 部署时 Portable 和 win-x64 有什么区别?

C# 到 C++ 的转换

c# - 如何获取 iTextSharp.text.pdf.parser.Vector 对象的 x、y、z 值?