当文件确实存在时,C#System.IO.FileNotFoundException

我正在尝试从ASP.NET Core中的操作返回文件:

public IactionResult GetFile(string filePath) {
    return File("/home/me/file.png","application/octet-stream");
}

但是,我得到一个

  

System.IO.FileNotFoundException

在我的浏览器窗口中:

  

处理请求时发生未处理的异常。   FileNotFoundException:找不到文件:/home/me/file.png

     

microsoft.AspNetCore.Mvc.Infrastructure.VirtualFileResultExecutor.ExecuteAsync(actionContext上下文,VirtualFileResult结果)

我尝试使用System.IO.File.Exists检查文件是否存在,并在Directory.GetFiles中查找文件,两者都说文件确实存在。我也尝试将媒体类型更改为image/png,但这无济于事。

为什么会出现此错误,该如何解决?

cdau9874 回答:当文件确实存在时,C#System.IO.FileNotFoundException

这是我在应用程序中使用的,并且效果很好:

   [HttpGet]
   [Route("download")]
   public async Task<iactionresult> Download([FromQuery] string file) {
       var uploads = Path.Combine(_hostingEnvironment.WebRootPath,"uploads");
       var filePath = Path.Combine(uploads,file);
       if (!System.IO.File.Exists(filePath))
           return NotFound();

       var memory = new MemoryStream();
       using (var stream = new FileStream(filePath,FileMode.Open))
       {
           await stream.CopyToAsync(memory);
       }
       memory.Position = 0;

       return File(memory,GetContentType(filePath),file);
   }

此摘录来自here:我的代码略有不同。

本文链接:https://www.f2er.com/3140512.html

大家都在问