我正在使用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 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 中打开文件并看到“文件已被另一个用户锁定”消息确认文件被锁定为问题。