C# 用C语言过滤文本文件#

C# 用C语言过滤文本文件#,c#,C#,如何打开扩展名为.txt的文件,我希望我的程序弹出一条错误消息,如果文件不是.txt文件,我希望下面有一个可以修改此代码的代码 private void button1_Click(object sender, EventArgs e) { OpenFileDialog of = new OpenFileDialog(); of.ShowDialog(); textBox1.Text = of.FileName; } 有人能帮忙吗,比如说我想把这个循环 if fileexte

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

private void button1_Click(object sender, EventArgs e)
{
   OpenFileDialog of = new OpenFileDialog();
   of.ShowDialog();
   textBox1.Text = of.FileName;
}
有人能帮忙吗,比如说我想把这个循环

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)
可以使用此方法

OpenFileDialog of = new OpenFileDialog();
if(of.ShowDialog() == DialogResult.OK)
{
    if(Path.GetExtension(of.FileName).Equals("txt",
                             StringComparison.InvariantCultureIgnoreCase))
                                textBox1.Text = of.FileName;
}

正如我正确理解的,您希望在对话框中只看到txt文件吗? 如果是,请使用属性

OpenFileDialog of = new OpenFileDialog();
of.Filter = "Text files (*.txt)|*.txt";

如果只允许txt扩展,则不应允许所有扩展

of.Filter = "Text Files|*.txt";

将使OpenFileDialog只接受txt扩展名文件。

+1-如果您只想使用文本文件,则只在对话框中显示文本文件。@Oded它可以工作,但它的i需要一个位置,如果我有一个文档文件,它将显示一个错误this@MildredShimz-重点是,有了这个,用户将无法选择
doc
docx
文件。错误1“System.Windows.Forms.DialogResult”不包含“Ok”的定义,并且找不到接受“System.Windows.Forms.DialogResult”类型的第一个参数的扩展方法“Ok”(是否缺少using指令或程序集引用?您可以将代码放入表单构造函数中,也可以在设计时设置筛选器属性。单击OpenFileDialog组件,转到属性窗口中的属性筛选器,并将其设置为“Text Files |*.txt”现在打开“文件”对话框时,您应该看到该对话框如何仅显示文件夹和txt文件。