Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
进程无法访问文件XXX,因为asp.net web api中的另一个进程正在使用该文件_Asp.net_Asp.net Mvc 3_Asp.net Web Api_Stream_Content Disposition - Fatal编程技术网

进程无法访问文件XXX,因为asp.net web api中的另一个进程正在使用该文件

进程无法访问文件XXX,因为asp.net web api中的另一个进程正在使用该文件,asp.net,asp.net-mvc-3,asp.net-web-api,stream,content-disposition,Asp.net,Asp.net Mvc 3,Asp.net Web Api,Stream,Content Disposition,我已经开发了ASP.NETWebAPI。我正在尝试读取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 FileControl

我已经开发了ASP.NETWebAPI。我正在尝试读取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;

            }
    }

您从不从
var fileStream=file.Open(路径,FileMode.Open)处理文件,使其处于锁定状态。

您从不从
var fileStream=file.Open(路径,FileMode.Open)处理文件,将其锁定。

我也使用block(自动调用dispose())打开了该文件,但即使这样也没有帮助。我将尝试显式调用dispose方法。我指出的这一行似乎没有必要,因为稍后您不会使用
fileStream
(您已经注释掉了它的使用)。我认为删除该行是安全的。使用
使用
块比手动调用dispose更可靠,因为它确保即使抛出异常也执行dispose。另一方面,您可以随时使用process explorer查看哪个进程正在锁定您的文件。@CodeCaster:我应该删除哪一行?@Giedrius:使用process explorer会让您受益匪浅。senseI也使用了block(它会自动调用dispose())打开了文件,但即使这样也没有帮助。我将尝试显式调用dispose方法。我指出的这一行似乎没有必要,因为稍后您不会使用
fileStream
(您已经注释掉了它的使用)。我认为删除该行是安全的。使用
使用
块比手动调用dispose更可靠,因为它确保即使抛出异常也执行dispose。另一方面,您可以始终使用process explorer查看哪个进程正在锁定您的文件。@CodeCaster:我应该删除哪一行?@Giedrius:使用process explorer很有意义您的fileStream变量未被使用,并且在创建StreamContent实例时,您还创建了新的fileStream实例,未释放。您的fileStream变量未被使用,并且在创建StreamContent实例时,您还创建了未释放的新fileStream实例。