Here is a cut-down version of what I am trying to do. I want to open an excel file into an Excel application, then alter the data in one of the sheets and resave the file. When I try to save, I get the error "The process cannot access the file because it is being used by another process".
The problem is that the file is still open after the Workbooks.Open. Is there any way that I can get the Excel process to release the file? I can make it release by doing a Marshal release on the Excel objects, but then I lose the data. I could store it external to the objects and re-add it, but I'd rather find a way to simply de-couple the file from the Excel objects in such a way that the file is closed. Is there a way to do that?
Microsoft.Office.Interop.Excel.Workbook workBook2;
Microsoft.Office.Interop.Excel.Application _application;
public void ReadAndSave(string path)
{
bool isLocked1 = IsFileStillInUse(path); // this returns false
_workBook = _application.Workbooks.Open(path);
bool isLocked2 = IsFileStillInUse(path); // this returns true
if (isLocked2)
{
// How can I get the file to release so I can resave it?
}
}
public static bool IsFileStillInUse(string filePath)
{
if (!File.Exists(filePath))
{
return false;
}
try
{
using (StreamReader reader = new StreamReader(File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
{
return false;
}
}
catch (IOException)
{
return true;
}
}