There is automation on excel on C #, it gives an error every time you save

Unhandled Exception: System.Runtime.InteropServices.COMException: Document not s aved. at Microsoft.Office.Interop.Excel._Workbook.SaveAs(Object Filename, Object Fi leFormat, Object Password, Object WriteResPassword, Object ReadOnlyRecommended, Object CreateBackup, XlSaveAsAccessMode AccessMode, Object ConflictResolution, O bject AddToMru, Object TextCodepage, Object TextVisualLayout, Object Local) 

How to save

 Workbook.SaveAs(Savefile, Excel.XlFileFormat.xlWorkbookNormal); Workbook.Close(Type.Missing, Type.Missing, Type.Missing); oWord.Workbooks.Close(); oWord.Quit(); 

It is necessary to do, if it gives an error, then repeat the save until I save it. I read what I can do through error handling or by checking the file, but I don’t know

  • Read about try-catch - Andrey NOP
  • Something is not a good idea. Well, let's say the user specified the path to which access is denied. That is, then your program will try to save forever? - VladD
  • Well, I think you can specify the number of save attempts - Protondx
  • one
    "Interop.Excel" is usually not a good idea - user227049

1 answer 1

To repeat the preservation or not, you can ask the user of the program.

 private void buttonOk_Click(object sender, RoutedEventArgs e) { bool isNotSaved = SaveToFile(); if (isNotSaved) { while (AskRepeatSaving()) { if (!SaveToFile()) break; } } } private bool SaveToFile() { try { //здесь логика сохранения в файл //... return false; } catch (Exception ex) { Debug.WriteLine($"<--Ошибка сохранения в файл: {ex.Message}"); return true; } } private bool AskRepeatSaving() { string message = "Возникла ошибка сохранения файла.\nПовторить попытку сохранения?"; string caption = "Ошибка сохранения файла"; var result = MessageBox.Show(message, caption, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes); return result == MessageBoxResult.Yes; }