C#SaveFileDialog

我正在使用savefiledialog来保存文件。 现在我需要检查名称是否已存在。

如果存在,则用户需要有机会更改名称或覆盖现有文件。

我已经尝试了所有的东西并搜索了很多但是找不到解决方案,而我在技术上认为它应该很容易。 在if( File.Exists(Convert.ToString(infor)) == trueFile.Exists(Convert.ToString(infor)) == true )中,必须进行检查。

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

只需使用SaveFileDialogOverwritePrompt属性:

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

可以在此处找到OverwritePrompt上的MSDN链接。

改为做到这一点

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

那应该为你做的工作

我会用这样的方法:

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

捕获exception而不是使用File.Exists实际上是唯一的方法,因为外部的东西可以在File.Exists之间创建文件并实际编写它,从而抛出你必须处理的exception。

此代码将循环并继续提示用户,直到文件成功写入。