0

我开发了ASP.NET web API。我正在尝试读取excel文件的内容并尝试将其作为字节返回。我收到以下错误:该进程无法访问文件XXX,因为它正被另一个进程在asp.net web api中使用

The process cannot access the file 'C:\app\MyHost.AppServices\bin\Debug\temp\888.xlsx' because it is being used by another process. 

我正在使用下面的code.I不知道是什么导致此错误。请提供您的建议

public class FileController : MyBase 
    { 
     public HttpResponseMessage Get(string id) 
     { 


      if (String.IsNullOrEmpty(id)) 
       return Request.CreateResponse(HttpStatusCode.BadRequest); 
      var path = Path.Combine("temp", id); 
      var fileStream = File.Open(path, FileMode.Open); 
      HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); 
      //response.Content = new StreamContent(fileStream); 


      response.Content = new StreamContent(new FileStream(path, FileMode.Open, FileAccess.ReadWrite)); 
      response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); 
      response.Content.Headers.ContentDisposition.FileName = id; 

      return response; 

      } 
    } 
+0

您的fileStream变量未使用,创建StreamContent实例时还创建了新的FileStream实例,该实例未处理。 – Giedrius

回答

3

您从不处置文件从var fileStream = File.Open(path, FileMode.Open);,让它锁定。

+0

我已经在使用block的帮助下打开了该文件(它自动调用dispose()),但即使这样也没有帮助。我会尝试明确地调用dispose方法 – SharpCoder

+0

我后面指出的这条线似乎是不必要的,因为稍后您不会使用'fileStream'(因为您已经注释了它的用法)。我认为删除这条线是安全的。 – CodeCaster

+1

使用'使用'块是比较确定的配置方式,比手动调用配置 - 因为它确保配置即使异常抛出也被执行。另一方面,您始终可以使用进程资源管理器来查看哪个进程正在锁定您的文件。 – Giedrius

相关问题