2012-04-21 62 views
1

如何打开带有.txt扩展名的文件,如果文件不是.txt文件,我希望我的程序弹出错误消息我想要一个可以在下面修改此代码的代码在C#中过滤文本文件

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) 

回答

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; 
} 
+0

我有一个错误,并突出显示在.ok – 2012-04-21 09:02:09

+0

错误'System.Windows.Forms.DialogResult'不包含'Ok'的定义,也没有扩展方法'Ok'接受第一个参数可以找到类型'System.Windows.Forms.DialogResult'(你是否缺少使用指令或程序集引用? – 2012-04-21 09:02:20

+0

@MildredShimz:corrected:Ok => OK。 – Tigran 2012-04-21 09:16:36

5

正如我的理解正确,你想在对话框中只看到txt文件? 如果是这样,请使用Filter属性。

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

+1 - 如果你只想使用文本文件,只显示对话框中的文本文件。 – Oded 2012-04-21 08:48:07

+0

@Oded它的工作原理,但我想要一个sitiuation,如果我有一个DOC文件,它显示一个错误,这个 – 2012-04-21 12:01:30

+1

@MildredShimz - 关键是,用这个,用户将无法选择“doc”或“docx”文件。 – Oded 2012-04-21 12:34:25

0

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

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

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

+0

我应该在哪里放这个代码? – 2012-04-21 09:00:40

+0

您可以将代码放在窗体构造函数中,也可以在设计时设置Filter属性。单击OpenFileDialog组件,然后转到属性窗口中的属性Filter,并将其设置为“Text Files | * .txt” – SimpleVar 2012-04-21 09:18:01

+0

当您打开文件对话框时,您应该看到文件对话框只显示文件夹和txt文件。 – SimpleVar 2012-04-21 09:18:24