我使用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中打开文件并查看“文件被另一个用户锁定”消息来锁定文件的事实。
最近的回复 - 我发现使用'.SaveAs'实际上导致ACE无法单独打开文件。当我在OutputStream中显式调用'Flush()'和'Dispose()'时,使用'File.InputStream'和'FileOutputStream'手动编写一个方法。 –
奇怪的是,如果你在'System.Web.HttpPostedFile'中'SaveAs'方法[看代码](http://referencesource.microsoft.com/#System.Web/HttpPostedFile.cs,4278efada0d8dbc4),这很好它做了什么 - 它创建一个'FileStream',然后将'InputStream'的内容写入它并调用'Flush'。 – RTPeat