I am uploading a file using HttpPostedFileBase.
The file uploads without an issue, but when I try and read from that file (excel file), I get an error saying that I can not read from the file as it is locked. How do I remove the lock from the file / make it not lock the file in the first place?
[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});
}
The above code reads the file and saves it without issue, but the below fails to then load that file:
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);
I have confirmed that it is the fact that the file is locked as the issue by opening the file in excel and seeing the “File is locked by another user” message.
All you need is
file.SaveAs(path);. You don’t need to flush or close thefile.InputStream. This will not lock the file.It is the code that is reading from it that is locking it. I see that you are using Office Interop in your ASP.NET MVC application. Don’t use it. This was never intended to be used in a multithreaded environment such as an ASP.NET application. The thing with Office Interop is that you actually need to have MS Office installed on the server which was never meant to be used that way. It’s the MS Office process that is locking the file, not your ASP.NET MVC application that simply stored it on the disk.
If you want to manipulate Office documents on the server you could use the OpenXML SDK.