使用两个扩展名保存文件



我试图通过使用SaveFileDialog保存文档。过滤器应该允许用户将文档保存为。doc或。docx,但如果用户设置为文件名'Test.txt',则文件将被保存为Test.txt,而不是Test.txt.doc

如何防止文件的类型转换,让用户只保存。doc或。docx文件?如果用户没有自己选择其中一个扩展名,它应该总是保存为。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并问它是否安全。文件名以。doc或。docx结尾,但这有点复杂,使SaveFileDialog的过滤器完全无用…

当我输入文件名'Test'时,输出将是Test.doc,当我输入'Test.txt'时,输出将是'Test.txt'

编辑:Ilyas的回答是正确的。它以。txt作为扩展名,但当我只是输入'Test'或'Test.doc'作为文件名时,它就不工作了,因为它总是将文件保存为'Test.doc.doc'。我当前的解决方案:
//.....
sfd.ShowDialog();
if (!sfd.FileName.EndsWith(".doc") && !sfd.FileName.EndsWith(".docx"))
    sfd.FileName += ".doc";

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

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时打印1.txt.doc。您可以自由地将检查或追加的逻辑提取到另一个方法中,以便使代码更具可读性

最新更新