Question

Here is my code:

        SaveFileDialog sd = new SaveFileDialog();
        sd.Title = "Select Excel Sheet to Export or Create New !";
        sd.Filter = "Excel files (*.xls)|*.xls";
        sd.FilterIndex = 0;

        sd.ShowDialog();

        if (sd.FileName != null)
        {
            AddWorksheetToExcelWorkbook(sd.FileName);
        }

Here is a simple 10 lines of code which i have been using for a very long time never any issue, but recently i am using this but i get error when i need to write to the file as below:

filename.. could not be found. Check the spelling of the file name, and verify that the file location is correct.

See image below its what we do , write filename and click save button , i only get error if i am making a new file not when i select existing. enter image description here

Why is this happening i have used this code many times, also i see there is no file created on the folder i save it to so why is the SaveFileDialog not saving files am i missing something?

UPDATE :

Work's fine if i select an already existing file issue only when i write name and press save.

Était-ce utile?

La solution

You need to call the OpenFile method in order to create or overwrite the file.

if (!String.IsNullOrEmpty(sd.FileName))
{
   using(var fileStream = sd.OpenFile())
   {
      //you can use the stream if you need it (otherwise just close it)
   }

   AddWorksheetToExcelWorkbook(sd.FileName);    
}

Caution from the MSDN page

For security purposes, this method creates a new file with the selected name and opens it with read/write permissions. This can cause unintentional loss of data if you select an existing file to save to. To save data to an existing file while retaining existing data, use the File class to open the file using the file name returned in the FileName property.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top