Search code examples
c#exceloffice-interop

Opening the SaveDialog intermittently crashes application


Good morning,

I have researched this to no end and have tried several solutions with no success. This anomaly happens maybe 1 in 4 attempts to save in testing. When the save button is clicked, the SaveDialog will start to appear, freeze for a second and shut down the application. I have tried [StaThread], but it did not help. Any suggestions would be appreciated. Thanks in advance. My code is below..

private void button4_Click(object sender, EventArgs e)
    {           
       try

        {

            using (SaveFileDialog SFD = new SaveFileDialog() { Filter = "Excel Workbook|*.xls", ValidateNames = true })
            {
                SFD.FileName = textBox11.Text.ToString();
                if (SFD.ShowDialog() == DialogResult.OK)

                {
                    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                    Workbook wb = app.Workbooks.Add(XlSheetType.xlWorksheet);
                    Worksheet ws = (Worksheet)app.ActiveSheet;
                    ws.Name = textBox11.Text.ToString();
                    app.Visible = false;

                    int i = 2;
                    foreach (ListViewItem item in lstLocal.Items)

                    wb.SaveAs(SFD.FileName, XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlLocalSessionChanges, Type.Missing, Type.Missing);
                    wb.Close();
                    app.Quit();
                    wb = null;
                    app = null;

                    MessageBox.Show("File has been saved!", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
        catch
        {
            MessageBox.Show("Something went wrong!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

Solution

  • For closure on this, it turned out to be an anomaly with my developing rig. I have since had to wipe it and re-install Win10/vS2017 for other reasons and the problem no longer exists. Compiled app on new install no longer has this issue on the developing rig or any others. Strange~ Thank you for the help and suggestions.