我正在使用保存文件对话框保存文件。现在我需要检查该名称是否已经存在。
如果它存在,用户需要有机会更改名称或覆盖已存在的文件。
我已经尝试了所有的东西,也搜索了很多次,但是我找不到一个解决方案,而从技术上来说,我认为它应该很容易做到。在if (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);
}
}发布于 2015-01-29 00:17:55
只需使用SaveFileDialog的OverwritePrompt属性即可
SaveFileDialog sfd = new SaveFileDialog{ Filter = ".xlsx Files (*.xlsx)|*.xlsx",
OverwritePrompt = true };可以在here上找到OverwritePrompt上的MSDN链接。
发布于 2015-01-29 00:16:56
改为这样做
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
sfd.OverwritePrompt = true;这应该可以为你做这些工作
发布于 2015-01-29 00:23:23
我会使用这样的方法:
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);捕获异常而不是使用File.Exists实际上是唯一的方法,因为外部的某些东西可以在File.Exists和实际写入它之间创建文件,从而抛出一个您无论如何都必须处理的异常。
此代码将循环并继续提示用户,直到文件成功写入。
https://stackoverflow.com/questions/28197046
复制相似问题