Reputation: 73
I have a requriement to upload a file and modify and then return the same. I dont need to save the file to any location but manipulate it and return. However I am not knowing how to return the file.
The below code allows the file to save, I even wrote code with out saving file. only problem is I am getting an error that this file is already open by someother user.
The process cannot access the file 'D:\Places\places\App_Data\877d36d3-ce29-48d1-995a-ea6652a528a7C2.xlsx' because it is being used by another process.
Can you please help me
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
if (uploadFile.ContentLength > 0)
{
string path = string.Empty;
var fileName = Path.GetFileName(uploadFile.FileName);
path = Path.Combine(Server.MapPath("~/App_Data/"), Guid.NewGuid() + fileName);
uploadFile.SaveAs(path);
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count;
(xlRange.Cells[4, 5] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 6] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 7] as Excel.Range).Value2 = "asdF";
(xlRange.Cells[4, 8] as Excel.Range).Value2 = "asdF";
releaseObject(xlWorksheet);
releaseObject(xlWorkbook);
releaseObject(xlApp);
GC.Collect();
uploadFile.InputStream.Dispose();
return File(path, "application/text");
}
else
{
return View();
}
}
private void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
//MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
}
finally
{enter code here
GC.Collect();
}
}
Upvotes: 3
Views: 6602
Reputation: 1
It's because probably you are not closing your file. You should use something like xlWorkbook.Close before trying to use it again, or you can use the using() statement.
http://msdn.microsoft.com/en-us/library/system.io.file.open(v=vs.71).aspx
Upvotes: 0
Reputation: 2619
in the action you can return a FileStreamResult
return new FileStreamResult([memory stream], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
You also might want to close and save the workbook to a temp area before returning. From the error it looks like the file is still open.
Upvotes: 3