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);
}
}
I would use an approach like this:
Catching an exception instead of using
File.Exists
is really the only way to do it, because something external could create the file betweenFile.Exists
and actually writing it, thus throwing an exception you'd have to handle anyway.This code will loop and continue to prompt the user until the file is successfully written.
Just use the
OverwritePrompt
property ofSaveFileDialog
:MSDN link on
OverwritePrompt
can be found here.do this instead
That should do the work for you