Reputation: 161
I want to save a file using the SaveFileDialog control. Why does the file need to already exist in order to save it?
This is the code I am using:
string month = dateTimePicker1.Value.Month.ToString();
string year = dateTimePicker1.Value.Year.ToString();
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = @"C:\";
saveFileDialog1.Title = "Save Sql Files";
saveFileDialog1.FileName = "MysqlBackup-"+month+"-"+year+".sql";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.DefaultExt = "Sql";
saveFileDialog1.Filter = "Sql files (*.Sql)|*.Sql";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// Here is the error. After typing in the filename, when I click OK it gives me an error stating that the file does not exist.
}
Upvotes: 1
Views: 11679
Reputation: 213
You need to set:
saveFileDialog.OverwritePrompt = true;
saveFileDialog.CreatePrompt = false;
OverwritePrompt: Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies a file name that already exists.
CreatePrompt: Gets or sets a value indicating whether the dialog box prompts the user for permission to create a file if the user specifies a file that does not exist.
Upvotes: 4
Reputation: 216263
This line requires that the file exists in the selected folder
saveFileDialog1.CheckFileExists = true;
set it to false and you could exit with OK if the file doesn't exist
Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.
Upvotes: 10