使用两个扩展名保存文件

时间:2013-05-29 09:04:53

标签: c# winforms savefiledialog

我正在尝试使用SaveFileDialog保存文档。 过滤器应允许用户将文档保存为.doc或.docx,但如果用户将文件保存为文件'Test.txt',则文件将保存为Test.txt而不是Test.txt.doc

如何阻止文件的类型转换并让用户只保存.doc或.docx文件?如果用户没有自己选择2个扩展中的一个,则应始终保存为.doc。

我目前的代码如下:

SaveFileDialog sfd = new SaveFileDialog();
string savepath = "";
sfd.Filter = "Wordfile (*.doc;*.docx;)|*.doc;*.docx)";
sfd.DefaultExt = ".doc";
sfd.SupportMultiDottedExtensions = true;
sfd.OverwritePrompt = true;
sfd.AddExtension = true;
sfd.ShowDialog();

//Save the document
doc.SaveAs(sfd.FileName, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);

我可以创建一个if并询问sfd.FileName是否以.doc或.docx结尾,但这有点复杂并且使得SaveFileDialog的Filter完全使用...

当我输入FileName'Test'时,输出将是Test.doc,当我输入'Test.txt'时,ouptout将是'Test.txt'

编辑:伊利亚斯的回答有点正确。它与.txt一起作为扩展,但不是当我只是输入'Test'或'Test.doc'作为文件名时,因为它总是将文件保存为'Test.doc.doc'。 我目前的解决方案:

//.....
sfd.ShowDialog();
if (!sfd.FileName.EndsWith(".doc") && !sfd.FileName.EndsWith(".docx"))
    sfd.FileName += ".doc";

编辑:解决方案可以在Ilyas的答案或我对Ilyas答案的评论中找到。

1 个答案:

答案 0 :(得分:1)

var sfd = new SaveFileDialog();
sfd.Filter = "Worddatei (*.doc;*.docx;)|*.doc;*.docx)";

Func<string, bool> isGoodExtension = path => new[]{".doc", ".docx"}.Contains(Path.GetExtension(path));

sfd.FileOk += (s, arg) => sfd.FileName += isGoodExtension(sfd.FileName) ? "" : ".doc";

sfd.ShowDialog();

//Save the document
Console.WriteLine (sfd.FileName);

如果输入1.txt.doc则打印1.txt。随意提取检查或附加到另一个方法的逻辑,以使代码更具可读性

相关问题