C# SaveFileDialog

2019-07-04 10:58发布

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);
    }
}

3条回答
ら.Afraid
2楼-- · 2019-07-04 11:31

I would use an approach like this:

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";

do
{
    if (sfd.ShowDialog() == DialogResult.OK)
    {
        string path = Path.GetDirectoryName(sfd.FileName);
        string filename = Path.GetFileNameWithoutExtension(sfd.FileName);

        try
        {
            toSave[i].SaveAs(infor);
            break;
        }
        catch (System.IO.IOException)
        {
            //inform user file exists or that there was another issue saving to that file name and that they'll need to pick another one.
        }
    }
} while (true);

MessageBox.Show("Succesvol opgeslagen als: " + infor);

Catching an exception instead of using File.Exists is really the only way to do it, because something external could create the file between File.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.

查看更多
贼婆χ
3楼-- · 2019-07-04 11:40

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.

查看更多
\"骚年 ilove
4楼-- · 2019-07-04 11:55

do this instead

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

That should do the work for you

查看更多
登录 后发表回答