简体   繁体   中英

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

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

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

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 eg "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 eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM