简体   繁体   English

保存带有可选扩展名的文件

[英]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.问题是我想要 2 个可选择的扩展名:-.txt -.md 因为我写的代码可以保存到任何类型的文件中(如果你没有放任何东西,我会保存为 .FILE),我只想要1 保存文件类型。 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:您需要根据模式设置对话框的 Filter 属性:

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:例如,在您的情况下,您似乎在说您希望保存对话框有一个组合下拉列表,其中包含两件事,一个是文本,另一个是 Markdown,您的过滤器有 4 件事:

.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"例如,您可以选择让它说Text files(*.txt)|*.txt - 括号中的文本与过滤器的工作方式无关,它实际上只是向用户显示,但它告诉他们“文件带有 .txt 扩展名”

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:脚注,如果您根据用户选择的内容保存不同的内容,则可能必须添加一些代码来检测 FileName 的扩展名,例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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