C# Web API下载锁文件

C# Web API下载锁文件,c#,asp.net,asp.net-mvc-4,asp.net-web-api,C#,Asp.net,Asp.net Mvc 4,Asp.net Web Api,我遇到了一个WebAPI方法的小问题,该方法在用户调用该方法的路由时下载一个文件 方法本身相当简单: public HttpResponseMessage Download(string fileId, string extension) { var location = ConfigurationManager.AppSettings["FilesDownloadLocation"]; var path = HttpContext.Current.Server.MapPath(

我遇到了一个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\u Data\pdfs\test file.pdf”,因为它正被 另一个过程

这个错误持续大约一分钟,然后我可以再次下载文件,但只能下载一次,然后我必须再等一分钟左右,直到文件解锁

请注意,我的文件相当大(100-800 MB)

我的方法中是否遗漏了什么?似乎流会将文件锁定一段时间或类似的时间


谢谢:)

这是因为您的文件被第一个流锁定,您必须指定一个允许多个流打开的文件:

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;
}
像这样,您允许多个流以只读方式打开此文件


请参阅关于该构造函数重载的说明。

如果您在using语句中声明流,它将在返回响应之前被释放,下载将失败。您是一个救生员Fabien!这样一个简单的解决方案——我只是目不转睛地看着自己:)我也考虑过使用语句——但正如您提到的,它没有任何意义,因为它将在返回调用之前被处理。非常感谢!:)@欢迎光临。一旦内容流被释放,文件流就会被释放,事实上,这应该是在客户端完成读取响应时。