在C#中过滤文本文件

时间:2012-04-21 08:41:49

标签: c#

如何打开扩展名为.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)

3 个答案:

答案 0 :(得分:6)

据我所知,您只想在对话框中看到txt文件? 如果是,请使用Filter属性。

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

答案 1 :(得分:1)

可以使用Path.GetExtension方法

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

答案 2 :(得分:0)

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

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

将使OpenFileDialog仅接受txt扩展文件。