Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a file with particular substring in name

Tags:

c#

I have a dirctory like this "C:/Documents and Settings/Admin/Desktop/test/" that contain a lot of microsoft word office files. I have a textBox in my application and a button. The file's name are like this Date_Name_Number_Code.docx. User should enter one of this options, my purpose is to search user entry in whole file name and find and open the file. thank you

like image 588
farshid nasseri Avatar asked Dec 01 '22 21:12

farshid nasseri


2 Answers

string name = textBox2.Text;
string[] allFiles = System.IO.Directory.GetFiles("C:\\");//Change path to yours
foreach (string file in allFiles)
    {
        if (file.Contains(name))
        {
            MessageBox.Show("Match Found : " + file);
        }
    }
like image 130
Mahdi Tahsildari Avatar answered Dec 26 '22 22:12

Mahdi Tahsildari


G'day,

Here's the approach I used. You'll need to add a textbox (txtSearch) and a button (cmdGo) onto your form, then wire up the appropriate events. Then you can add this code:

    private void cmdGo_Click(object Sender, EventArgs E)
    {
        //  txtSearch.Text = "*.docx";

        string[] sFiles = SearchForFiles(@"C:\Documents and Settings\Admin\Desktop\test", txtSearch.Text);
        foreach (string sFile in sFiles)
        {
            Process.Start(sFile);
        }
    }

    private static string[] SearchForFiles(string DirectoryPath, string Pattern)
    {
        return Directory.GetFiles(DirectoryPath, Pattern, SearchOption.AllDirectories);
    }

This code will go off and search the root directory (you can set this as required) and all directories under this for any file that matches the search pattern, which is supplied from the textbox. You can change this pattern to be anything you like:

  • *.docx will find all files with the extention .docx
  • *foogle* will find all files that contain foogle

I hope this helps.

Cheers!

like image 40
Rastus7 Avatar answered Dec 26 '22 21:12

Rastus7