简体   繁体   English

Web API下载锁定文件

[英]Web API download locks file

I'm having a small issue with a WebAPI method that downloads a file when the user calls the route of the method. 我遇到一个WebAPI方法的小问题,当用户调用方法的路由时,该方法会下载文件。

The method itself is rather simple: 方法本身很简单:

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;
}

The method works as expected - the first time I call it. 该方法按预期工作 - 我第一次调用它。 The file is transmitted and my browser starts downloading the file. 传输文件,我的浏览器开始下载文件。

However - if I call the same URL again from either my own computer or from any other - I get an error saying: 但是 - 如果我从我自己的计算机或任何其他计算机再次调用相同的URL - 我收到一条错误消息:

The process cannot access the file 'D:\\...\\App_Data\\pdfs\\test-file.pdf' because it is being used by another process. 该进程无法访问文件'D:\\ ... \\ App_Data \\ pdfs \\ test-file.pdf',因为它正由另一个进程使用。

This error persists for about a minute - and then I can download the file again - but only once - and then I have to wait another minute or so until the file is unlocked. 这个错误持续了大约一分钟 - 然后我可以再次下载文件 - 但只能一次 - 然后我必须等待一分钟左右,直到文件解锁。

Please note that my files are rather large (100-800 MB). 请注意我的文件相当大(100-800 MB)。

Am I missing something in my method? 我在方法中遗漏了什么吗? It almost seems like the stream locks the file for some time or something like that? 它似乎流文件锁定文件一段时间或类似的东西?

Thanks :) 谢谢 :)

It is because your file is locked by the first stream, you must specify a FileShare that allow it to be opened by multiple streams : 这是因为您的文件被第一个流锁定,您必须指定一个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;
}

Like that you allow multiple stream to open this file for read only. 像这样你允许多个流打开这个文件只读。

See the MSDN documentation on that constructor overload. 请参阅有关该构造函数重载的MSDN文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM