2012-10-08 101 views
0

我使用HttpPostedFileBase上传文件。 文件上传没有问题,但是当我尝试从该文件(excel文件)中读取时,出现一条错误消息,说明文件被锁定时无法读取该文件。如何从文件中移除锁定/使其不锁定文件?HttpPostedFileBase锁定文件

[HttpPost] 
     public ActionResult Index(HttpPostedFileBase file) 
     { 
      string path = string.Empty; 
      if (file.ContentLength > 0) 
      { 
       var fileName = Path.GetFileName(file.FileName); 
       path = Path.Combine(Server.MapPath("~/App_Data/"), Guid.NewGuid() + fileName); 
       file.SaveAs(path); 
       file.InputStream.Flush(); 

       file.InputStream.Close(); 
       file.InputStream.Dispose(); 

       // Import the file 
       ViewData["FileName"] = fileName; 
       //Added to ensure that the file had finished being written by the time  I try and read it 
       System.Threading.Thread.Sleep(2000); 
      } 

      return RedirectToAction("Index", new{fileName = path}); 
     } 

上述代码读取该文件,并将其保存没有问题,但低于未能然后加载文件:

VAR =簿excelApp.Workbooks.Open(ExcelDocumentLocation, Missing.Value ,Missing.Value,Missing.Value,Missing.Value, Missing.Value,Missing.Value,Missing.Value,Missing.Value, Missing.Value,Missing.Value,Missing.Value,Missing.Value, 失踪。值,Missing.Value);

我确认这是通过在Excel中打开文件并查看“文件被另一个用户锁定”消息来锁定文件的事实。

回答

3

所有你需要的是file.SaveAs(path);。您不需要刷新或关闭file.InputStream。这将不锁该文件。

这是正在读取的代码正在锁定它。我看到您在ASP.NET MVC应用程序中使用Office Interop。不要使用它。这从来没有打算用于多线程环境,如ASP.NET应用程序。 Office Interop的事情是,您实际上需要在服务器上安装MS Office,而这种服务器永远不会被这样使用。它是锁定文件的MS Office进程,而不是将它简单地存储在磁盘上的ASP.NET MVC应用程序。

如果要在服务器上操作Office文档,可以使用OpenXML SDK

+1

最近的回复 - 我发现使用'.SaveAs'实际上导致ACE无法单独打开文件。当我在OutputStream中显式调用'Flush()'和'Dispose()'时,使用'File.InputStream'和'FileOutputStream'手动编写一个方法。 –

+0

奇怪的是,如果你在'System.Web.HttpPostedFile'中'SaveAs'方法[看代码](http://referencesource.microsoft.com/#System.Web/HttpPostedFile.cs,4278efada0d8dbc4),这很好它做了什么 - 它创建一个'FileStream',然后将'InputStream'的内容写入它并调用'Flush'。 – RTPeat