FileStream无法访问该文件,因为它正由另一个进程使用

时间:2012-11-08 20:41:41

标签: asp.net filestream savefiledialog response.addheader

我是ASP.NET新手,我遇到了这个问题。

我有一个页面,有一个Button可以下载以前存储在SharePoint页面中的template.xls。我有下载方法,它工作得很好。有问题的模板将保存在我的本地IIS上的Web应用程序所在的文件夹中。 问题是打开此文件给最终用户。我需要向用户显示一个弹出窗口,这样他就可以打开/保存这个template.xls 我正在使用以下内容:

//path on my local IIS where the file is located after the download
string _strFolderApp = "~/Arq/";
string _strFullFolderApp = _strFolderApp + _strFileName;
string apPath = System.Web.Hosting.HostingEnvironment.MapPath(_strFullFolderApp);

FileStream _FileStream = new FileStream(apPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
// Writes a block of bytes to this stream using data from a byte array.
_FileStream.Write(_contentFile, 0, _contentFile.Length);

//opens the file
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + _strFileName);
Response.ContentType = "";
Response.TransmitFile(apPath);
Response.Flush();
File.Delete(apPath);
Response.End();
# endregion

// close file stream
_FileStream.Close();

我在线搜索,所有答案最终都使用FileShare.ReadWrite,因此这两个过程都能正常运行。但它对我不起作用,因为当代码到达 Response.TransmitFile(apPath); 时,我得到一个异常并且弹出窗口没有显示。 例外:

该进程无法访问文件'c:\ inetpub \ wwwroot \ MyWebApp \ File \ TemplateSharePoint.xlsx',因为它正由另一个进程使用。

请提供任何帮助:)

修改 代码更新

if (_flgSPSDownload)
        {
            System.IO.FileStream _FileStream = new System.IO.FileStream(apPath,System.IO.FileMode.Create, System.IO.FileAccess.Write);
            _FileStream.Write(_contentFile, 0, _contentFile.Length);
            _FileStream.Close();


            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=" + _strFileName);
            //Set the appropriate ContentType.
            Response.ContentType = "Application/x-msexcel";
            Response.TransmitFile(apPath);
            Response.Flush();
            //Write the file directly to the HTTP content output stream.
            Response.WriteFile(apPath);
            //File.Delete(apPath);

            //Process.Start(_strDestinationPath + "//" + _strFileName);

2 个答案:

答案 0 :(得分:1)

据我所知,你打开文件流,然后在关闭之前再次尝试打开它。

首次打开文件:

FileStream _FileStream = new FileStream(apPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

Response.TransmitFile(apPath); 

似乎试图再次打开该文件。

我建议打电话

_FileStream.Close();

在致电TransmitFile之前。

答案 1 :(得分:0)

我通过另一种方式解决了这个问题

我打开窗口任务管理器 并发现我的项目的dll文件正在运行

倍数(我的意思是它的副本存在) 我删除它们,而不是我的问题解决了

相关问题