Search code examples
c#.netwinformssavefiledialog

SaveFileDialog - (File path) does not exist. Verify that the correct file name was given


I want to save a new filename but now I can only save rewrite files. Every time I tried saving a new filename, a message box appears with a warning dialog:

(File path) does not exist. Verify that the correct file name was given."

Below is my code, can anyone please point out what is missing? Thank you.

private void button5_Click(object sender, EventArgs e)
{
    SaveFileDialog saveFileDialog1 = new SaveFileDialog();
    saveFileDialog1.Title = "Save File";
    saveFileDialog1.CheckFileExists = true;
    saveFileDialog1.CheckPathExists = true;
    saveFileDialog1.Filter = "Text files (*.txt)|*.txt| CONF(*.conf)|*.conf|All files (*.*)|*.*";
    saveFileDialog1.FilterIndex = 2;
    saveFileDialog1.ShowDialog();

    if (saveFileDialog1.FileName != "")
    {
        // Saves the Image via a FileStream created by the OpenFile method.  
        System.IO.FileStream fs = (System.IO.FileStream)saveFileDialog1.OpenFile();
        // Saves the Image in the appropriate ImageFormat based upon the  
        // File type selected in the dialog box.  
        // NOTE that the FilterIndex property is one-based.  
        switch (saveFileDialog1.FilterIndex)
        {
            case 1:
                saveFileDialog1.FileName = saveFileDialog1.FileName + ".txt";
                break;
            case 2:
                saveFileDialog1.FileName = saveFileDialog1.FileName + ".conf";
                break;
            default:
                saveFileDialog1.FileName = saveFileDialog1.FileName + ".txt";
                break;
        }

        fs.Close();
    }
}

Solution

  • You need to set CheckFileExists and CheckPathExists to false to prevent the dialog checking existence of the file, otherwise the dialog box displays a warning if the user specifies a path:

    saveFileDialog1.CheckFileExists = false;
    saveFileDialog1.CheckPathExists = false;