我开发了 ASP.NET Web API。我正在尝试读取 excel 文件的内容并尝试将其作为字节返回。我收到以下错误:
The process cannot access the file 'C:appMyHost.AppServicesbinDebugtemp888.xlsx' because it is being used by another process.
我正在使用下面的代码。我不确定是什么导致了此错误。请提供您的建议
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;
}
}
您永远不会从var fileStream = File.Open(path, FileMode.Open);
中释放文件,使其保持锁定状态。