'Saving File with selectable extensions

So I made code again about saving files (you can select file name) here:

private void button3_Click(object sender, EventArgs e)
    {
        SaveFileDialog saveFileDialog1 = new SaveFileDialog();
        if (saveFileDialog1.ShowDialog() == DialogResult.OK)
        {
            using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
            using (StreamWriter sw = new StreamWriter(s))
            {
                sw.Write(fastColoredTextBox1.Text);
            }
        }
    }

the problem is I want to have 2 selectable extensions: -.txt -.md because the code I wrote can save to any type of file(and if you didn't put anything I will save as . FILE) and I just want only 1 save file type. Save dialog



Solution 1:[1]

You need to set the dialog's Filter property according to the pattern:

Text to show|Filter to apply|Text to show 2|Filter to apply 2|...

For example in your case, where you seem to be saying you want the save dialog to have a combo dropdown containing two things, one being Text and the other being Markdown, your Filter has 4 things:

.Filter = "Text files|*.txt|Markdown files|*.md";

It is typical to put the filter you will apply into the text you will show too, so the user can see what you mean by e.g. "Text files" but I've left that out for clarity.

For example you might choose to make it say Text files(*.txt)|*.txt - the text in the parentheses has no bearing on the way the filter works, it's literally just shown to the user, but it tells them "files with a .txt extension"

Footnote, you may have to add some code that detects the extension from the FileName if you're saving different content per what the user chose e.g.:

var t = Path.GetExtension(saveFileDialog.FileName);
if(t.Equals(".md", StringComparison.OrdinalIgnoreCase))
  //save markdown 
else
  //save txt

Solution 2:[2]

You can just use the filter of your dialog to set the allowed extensions:

// Filter by allowed extensions
saveFileDialog1.Filter = "Allowed extensions|*.txt;*.md";

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Jonas Metzler