我正在使用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});
}上面的代码读取文件并保存它,没有问题,但是下面的代码无法加载该文件:
var工作簿= excelApp.Workbooks.Open(ExcelDocumentLocation,Missing.Value,Missing.Value,Missing.Value);
我已经确认,通过在excel中打开文件并看到“文件被另一个用户锁定”消息,文件被锁定为问题。
发布于 2012-10-08 10:05:17
你只需要file.SaveAs(path);。您不需要刷新或关闭file.InputStream。这将不会锁定文件。
是正在读取的代码锁定了它。我看到您在ASP.NET MVC应用程序中使用Office。别用它。这在多线程环境(如ASP.NET应用程序)中从未使用过。Office的特点是,您实际上需要在服务器上安装MS Office,而这从来就不是以这种方式使用的。锁定文件的是MS进程,而不是仅仅将其存储在磁盘上的ASP.NET MVC应用程序。
如果要在服务器上操作Office文档,可以使用OpenXML SDK。
https://stackoverflow.com/questions/12779276
复制相似问题