Saeed Mousazadeh
Saeed Mousazadeh

Reputation: 69

How to search in a folder by the name or extension of a file in winForm in C#?

First of all we should get a directory by the user. then in the specified folder we want to search a file by its name or its extension. for example in that folder we want to search a name "Book" or an extension like .txt . Suppose that we have a Browse button, and by clicking on it we get the path and show it in a label(in the below code it is label1). and we have a Search button and a textBox that we should write the name or extension in textBox and by clicking on Search button the result(the founded files' names) would be shown in a MessageBox.
i have written a piece of code that only gets the path and i don't know how to write the rest.

private void Browse_Click(object sender, EventArgs e)
{
    if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
    {
        this.label1.Text = folderBrowserDialog1.SelectedPath;
        Directory = label1.ToString();
    }
}

Upvotes: 0

Views: 1814

Answers (2)

Idle_Mind
Idle_Mind

Reputation: 39132

Here's a simple example of using Directory.GetFiles() with a search pattern:

    private void Browse_Click(object sender, EventArgs e)
    {
        if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
        {
            string[] matches = Directory.GetFiles(folderBrowserDialog1.SelectedPath, "*book*"); // use "*.txt" to find all text files
            if (matches.Length > 0)
            {
                foreach (string file in matches)
                {
                    Console.WriteLine(file);
                }
            }
            else
            {
                MessageBox.Show("No matches found!");
            }
        }
    }

Upvotes: 1

J1B
J1B

Reputation: 178

suppose your search button's click event use following function

private void Search_Click(object sender, EventArgs e)
{
    DirectoryInfo Di=new DirectoryInfo(label1.Text);
    foreach(FileInfo fi in Di.GetFiles())
    {
       textbox.Text+=fi.Name+"\r\n";
    }
}

Upvotes: 0

Related Questions