简体   繁体   中英

Find a file with particular substring in name

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

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);
        }
    }

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!

You can use Directory.GetFiles($path$).Where(file=>file.Name.Contains($user search string$) .

Should work for you.

You can use the Directory.GetFiles(string, string) which searches for a pattern in a directory. So, for your case, this would be something like:

 string[] files =
          Directory.GetFiles("C:/Documents and Settings/Admin/Desktop/test/",
                              "Date_Name_Number_Code.docx");

Then look through the files array for what you are looking for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM