我在使用WebAPI方法时遇到一个小问题,该方法在用户调用该方法的路由时下载文件。
该方法本身非常简单:
public HttpResponseMessage Download(string fileId, string extension)
{
var location = ConfigurationManager.AppSettings["FilesDownloadLocation"];
var path = HttpContext.Current.Server.MapPath(location) + fileId + "." + extension;
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
该方法按预期工作-我第一次调用它。文件已传输,我的浏览器开始下载文件。
但是-如果我从自己的计算机或任何其他计算机上再次调用相同的URL-我会收到一条错误消息:
该进程无法访问文件'D:\ ... \ App_Data \ pdfs \ test-file.pdf',因为该文件正在被另一个进程使用。
该错误持续大约一分钟-然后我可以再次下载该文件-但只能下载一次-然后我必须等待一分钟左右,直到该文件被解锁。
请注意,我的文件很大(100-800 MB)。
我的方法中缺少什么吗?似乎流似乎将文件锁定了一段时间或类似的东西?
谢谢 :)
这是因为文件被第一个流锁定,因此必须指定一个FileShare,以允许它由多个流打开:
public HttpResponseMessage Download(string fileId, string extension)
{
var location = ConfigurationManager.AppSettings["FilesDownloadLocation"];
var path = HttpContext.Current.Server.MapPath(location) + fileId + "." + extension;
var result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
这样,您就可以允许多个流打开此文件以进行只读。
有关该构造函数重载的信息,请参见MSDN文档。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句