Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/265.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
当文件确实存在时,C#System.IO.FileNotFoundException_C#_Asp.net Core Mvc_System.io.file - Fatal编程技术网

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

当文件确实存在时,C#System.IO.FileNotFoundException,c#,asp.net-core-mvc,system.io.file,C#,Asp.net Core Mvc,System.io.file,我正在尝试从ASP.NET Core中的操作返回文件: public IActionResult GetFile(string filePath) { return File("/home/me/file.png", "application/octet-stream"); } 然而,我得到了一份工作 System.IO.FileNotFoundException 在我的浏览器窗口中: 处理请求时发生未处理的异常。 FileNotFoundException:找不到文件:/home/m

我正在尝试从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
检查文件是否存在,并在
目录.GetFiles
中查找它,这两个目录都表示文件确实存在。我还尝试将媒体类型更改为
image/png
,但这没有任何帮助


为什么会出现此错误,以及如何修复此错误?

这是我在应用程序中使用的,它可以完美地工作:

   [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);
   }
[HttpGet]
[路线(“下载”)]
公共异步任务下载([FromQuery]字符串文件){
var uploads=Path.Combine(_hostingEnvironment.WebRootPath,“uploads”);
var filePath=Path.Combine(上传,文件);
如果(!System.IO.File.Exists(filePath))
返回NotFound();
var memory=newmemoryStream();
使用(var stream=newfilestream(filePath,FileMode.Open))
{
等待流。CopyToAsync(内存);
}
记忆位置=0;
返回文件(内存、GetContentType(文件路径)、文件);
}

此代码段来自:我的代码稍有不同。

将上述行包装在try catch中,然后在catch中放置断点。我想试试……你需要使用完整路径来获取文件。我会将该路径放入一个设置中。此外,我会将该文件作为字节数组读取,并将其传递给结果。该文件位于服务器或客户端计算机中?@MarioVernari我尝试过,但始终没有找到答案。这工作得很好,但是除了您答案中的代码外,我还必须通过链接复制GetContentType方法。