Mildred Shimz
Mildred Shimz

Reputation: 617

Filtering text files in C#

How do I just open files with the .txt extension, I want to my program to pop up an error message if the file is not a .txt file I want a code that can modify this code below

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

Can someone help let's say I want to put this loop

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)

Upvotes: 3

Views: 6330

Answers (3)

Tigran
Tigran

Reputation: 62265

Can use Path.GetExtension method for this

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

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14542

You shouldn't allow all extensions if you only allow txt extension.

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

Will make the OpenFileDialog accept only txt extension files.

Upvotes: 0

Sergey Podolsky
Sergey Podolsky

Reputation: 157

As I understood correctly, you want to see only txt files in your dialog? If so, use Filter property.

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

Upvotes: 9

Related Questions