我开发了ASP.NET Web API。我试图读取excel文件的内容并尝试将其作为字节返回。我收到了以下错误:
The process cannot access the file 'C:\app\MyHost.AppServices\bin\Debug\temp\888.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;
}
}
答案 0 :(得分:3)
您永远不会从var fileStream = File.Open(path, FileMode.Open);
处置文件,而是将其锁定。