在C#中过滤文本文件

Mil*_*imz 2 c#

我如何只打开扩展名为.txt的文件,如果文件不是.txt文件,我希望我的程序弹出错误信息我想要一个可以在下面修改此代码的代码

private void button1_Click(object sender, EventArgs e)
{
   OpenFileDialog of = new OpenFileDialog();
   of.ShowDialog();
   textBox1.Text = of.FileName;
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我们说我想把这个循环

if fileextension is .txt then 
OpenFileDialog of = new OpenFileDialog();
            of.ShowDialog();
            textBox1.Text = of.FileName;
else show error message(like can not open this file)
Run Code Online (Sandbox Code Playgroud)

use*_*260 6

据我所知,你想在对话框中看到只有txt文件?如果是这样,请使用Filter属性.

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Text files (*.txt)|*.txt";
Run Code Online (Sandbox Code Playgroud)

  • +1 - 如果您只想使用文本文件,则仅在对话框中显示文本文件。 (2认同)
  • @MildredShimz - 关键是这样,用户将无法选择 `doc` 或 `docx` 文件。 (2认同)