I am using the FolderBrowserDialog to let the user select a location to save files, and/or create a new folder. It is working 99% of the time, however in some instances when the user clicks the Create New Folder button, changes the name, then clicks okay an exception will be thrown that "New Folder" does not exist.
It seems the code is still looking for a folder with the name "New Folder" even though the user renamed it. What could I change in my code to handle this issue so that the files are always saved in the folder the user selects?
//Declaring Filename
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
folderDlg.Description = "Choose the location to save Files";
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
savelocation = folderDlg.SelectedPath;
}
// Choose whether to write header. Use EnableWithoutHeaderText instead to omit header.
dataGridExport.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
// Select all the cells
dataGridExport.SelectAll();
// Copy selected cells to DataObject
DataObject dataObject = dataGridExport.GetClipboardContent();
// Get the text of the DataObject, and serialize it to a file
File.WriteAllText(savelocation + "\\ExcelExport.csv", dataObject.GetText(TextDataFormat.CommaSeparatedValue));
It's unlikely to be a bug in your code; the user creates a new folder inside the FBD, FBD captures path as
...\new folder, user clicks it again (to rename it), renames it, then doesn't click it yet again (or click off it and back on) for FBD to realise the name has changed. Not your fault/problem; PEBKAC/PICNIC. Every windows software that used FBD suffers this.As an side, FBD is a horrible thing, avoid using it (you can't always quickly paste a path into it to go there.. You must laboriously find your way through many directories using the mouse. It gets even more irritating when the initial directory selected by the FBD is reset to some default/not near what the user chose last time etc)
Use an OpenFileDialog instead and simultaneously prompt the user for a file name to save, or perhaps take a look at an SO question like How do you configure an OpenFileDialog to select folders? to see what people have done to get around the limitations of the FBD