Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SaveFileDialog

I am using the savefiledialog to save a file. Now I need to check if the name already exists.

If it exists the user needs to get a chance to change the name or overwrite the already existing file.

I have tried it with everything and searched a lot but can't find a solution while I technically think it should be easy to do. In the if (File.Exists(Convert.ToString(infor)) == true) the check must take place.

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
if (sfd.ShowDialog() == DialogResult.OK)
{
    string path = Path.GetDirectoryName(sfd.FileName);
    string filename = Path.GetFileNameWithoutExtension(sfd.FileName);

    for (int i = 0; i < toSave.Count; i++)
    {
        FileInfo infor = new FileInfo(path + @"\" + filename + "_" + exportlist[i].name + ".xlsx");
        if (File.Exists(Convert.ToString(infor)) == true)
        {

        }
        toSave[i].SaveAs(infor);
        MessageBox.Show("Succesvol opgeslagen als: " + infor);
    }
}
like image 226
EfhK Avatar asked Feb 12 '23 01:02

EfhK


1 Answers

Just use the OverwritePrompt property of SaveFileDialog:

SaveFileDialog sfd = new SaveFileDialog{ Filter = ".xlsx Files (*.xlsx)|*.xlsx",
                                         OverwritePrompt = true };

MSDN link on OverwritePrompt can be found here.

like image 113
Corey Adler Avatar answered Feb 13 '23 21:02

Corey Adler