0

I am trying to rename my Excel Workbook. Currently I am just saving the file name from my program, but I do not want a message that asks if I want to overwrite the file that already exists, which is my current issue. Having a temporary file name may not be the way to go about doing this so if there are better recommendations please inform me.

Without the excelWorkbook.SaveAs("Test Name"); line, the file gives a random tmp name.

 private void excelfunc()
        {
            string tempPath = System.IO.Path.GetTempFileName();

            System.IO.File.WriteAllBytes(tempPath, Properties.Resources.excelResource);

            Excel.Application excelApplication = new Excel.Application();
            Excel._Workbook excelWorkbook;
            excelWorkbook = excelApplication.Workbooks.Open(tempPath);
            excelWorkbook.SaveAs("Test Name");
            excelApplication.Visible = true; // at this point its up to the user to save the file

        }

UPDATE: I added in a line that overwrites the existing file, but I am now getting an error message that says: "System.IO.IOException: 'Cannot create a file when that file already exists."

 private void excelfunc()
        {
            string tempPath = System.IO.Path.GetTempFileName();
            MessageBox.Show(tempPath);
            System.IO.File.WriteAllBytes(tempPath, Properties.Resources.excelResource);

            Excel.Application excelApplication = new Excel.Application();
            Excel._Workbook excelWorkbook;
            File.Move(tempPath, "Test Name");
            excelWorkbook = excelApplication.Workbooks.Open(tempPath);         
            excelApplication.Visible = true; // at this point its up to the user to save the file
}
okra
  • 7
  • 5
  • https://stackoverflow.com/questions/25154717/how-to-save-overwrite-existing-excel-file-without-message – Roman Ryzhiy Dec 07 '22 at 16:26
  • You don't need to have Excel installed to generate Excel files. You can use a library like EPPlus, ClosedXML or NPOI to create an Excel file on the fly and save it anywhere you want – Panagiotis Kanavos Dec 07 '22 at 16:27

1 Answers1

0

System.IO.File.Move("oldfilename", "newfilename");

Chris Phillips
  • 1,997
  • 2
  • 19
  • 34
  • Given this is identical to [this answer](https://stackoverflow.com/a/3218923/134204) it would be better to either vote to close as a duplicate or add a comment. Besides, the OP really asks how to overwrite an existing Excel file, not how to rename a file – Panagiotis Kanavos Dec 07 '22 at 16:29
  • Are you trying to apply .NET Framework to VBA? – S Nash Dec 07 '22 at 16:43
  • @SNash - I'm not sure what you mean. There isn't any indication that the code above is in VB, and the question is tagged as C#. `System.IO.File.Move` is valid C# all the way up to .NET 7. – Chris Phillips Dec 07 '22 at 16:52