HttpPostedFileBase 锁定文件

Ben*_*Ben 0 c# asp.net-mvc asp.net-mvc-4

我正在使用HttpPostedFileBase. 文件上传没有问题,但是当我尝试从该文件(excel 文件)中读取时,我收到一条错误消息,说我无法从文件中读取,因为它已被锁定。如何从文件中删除锁定/使其首先不锁定文件?

[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});
        }
Run Code Online (Sandbox Code Playgroud)

上面的代码读取文件并保存它没有问题,但下面的代码无法加载该文件:

var workbook = 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, Missing.Value);

我已经通过在 excel 中打开文件并看到“文件被另一个用户锁定”消息来确认文件被锁定为问题。

Dar*_*rov 5

您只需要file.SaveAs(path);. 您不需要刷新或关闭file.InputStream. 这不会锁定文件。

正是读取它的代码锁定了它。我看到您在 ASP.NET MVC 应用程序中使用了 Office Interop。不要使用它。这从未打算在多线程环境中使用,例如 ASP.NET 应用程序。Office Interop 的问题在于,您实际上需要在服务器上安装 MS Office,而这并不意味着要以这种方式使用。锁定文件的是 MS Office 进程,而不是简单地将文件存储在磁盘上的 ASP.NET MVC 应用程序。

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