Reputation: 2828
I am trying to SaveAs() a sheet to csv file and immediately after load that csv file into string, using C# VSTO. The issue is that unless I Close() the workbook I can't access newly created csv file. The error is related to "file locked" issue. If I close the workbook or copy it to blank workbook then I always able to access that file, however these are not ideal solutions. Any ideas, on how to avoid file lock?
Excel.Worksheet sheet = workbook.Sheets[sheetName];
sheet.Activate();
sheet.Unprotect();
sheet.SaveAs(fileName, Excel.XlFileFormat.xlCSV, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(); <-- Don't want that happen
// Get the Input CSV.
string contents = File.ReadAllText(InputCsvFileName);
Upvotes: 1
Views: 646
Reputation: 1899
The reason for this @Jim is that with the SaveAs method you are no longer in the 'old' -source- Worksheet but in the file you -targeted- in the SaveAs. Keep in mind that the changes made -after- opening the 'source' workbook are not persisted in the 'source' but are persisted in the 'target' (SaveAs) workbook.
So if you started working in WorkbookA.xlsm, activated SheetA, Saved SheetA as SheetA.csv you are now in SheetA.csv in Excel.
(Note: If you do this manually or by running VBA manually this has a strange side effect that if your source contained two sheets the .csv also appears to have two sheets but after re-opening the .csv only the saved sheet was persisted)
From this you can say that if you plan to continue to work in the -source- the meta steps are:
Upvotes: 3