File does not exist verify if file name exist SaveFileDialog?

只愿长相守 提交于 2019-12-25 02:21:33

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/13762416/file-does-not-exist-verify-if-file-name-exist-savefiledialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!