Question

I'm trying to save a document by using SaveFileDialog. The filter should allow the user to save the document as .doc or .docx, but if the user tpyes as filename 'Test.txt', the file is being saved as Test.txt and not Test.txt.doc

How do I prevent the type conversion of the file and let the user only save .doc or .docx files? If the user doesn't pick one of the 2 extension by himself, it should always save as .doc.

My current code looks like this:

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

I could make an if and ask if sfd.FileName ends with .doc or .docx, but this is kinda complicated and makes the Filter for SaveFileDialog totally useles...

When I type the FileName 'Test', the output would be Test.doc, when I type 'Test.txt', the ouptout would be 'Test.txt'

Edit: Ilyas answer is kinda correct. It works with .txt as extension, but not when I just type 'Test' or 'Test.doc' as filename, because it will always save the file as 'Test.doc.doc'. My current solution:

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

edit: Solution can be found in Ilyas answer or my comment on Ilyas answer.

Était-ce utile?

La solution

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

Prints 1.txt.doc if a enter 1.txt. Feel free to extract logic of checking or appending into another method, so to make code more readable

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top