C#SaveFileDialog
我正在使用savefiledialog来保存文件。 现在我需要检查名称是否已存在。
如果存在,则用户需要有机会更改名称或覆盖现有文件。
我已经尝试了所有的东西并搜索了很多但是找不到解决方案,而我在技术上认为它应该很容易。 在if( File.Exists(Convert.ToString(infor)) == true
( File.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); } }
只需使用SaveFileDialog
的OverwritePrompt
属性:
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。
此代码将循环并继续提示用户,直到文件成功写入。
上述就是C#学习教程:C#SaveFileDialog分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/998569.html