C# – File does not exist verify if file name exist SaveFileDialog

csavefiledialog

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.
    }

Best Answer

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

CheckFileExists on MSDN

Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

Related Topic