Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find folders and files by its partial name c#

Tags:

c#

in a specific folder of my hard drive i have stored many other sub folder and files. now i want to list those folders and files name by their partial name.

for example
--------------
c webapi xx           folder
c mvctutorial xx      folder
done webapi xx        folder
webapi done           folder
webapi.zip            file
mvc.iso               file

now when i like to search by partial name webapi then i want to get list of files and folders name which has webapi word. i want to show their full folder or file name in grid with their full path and size. like below way.

Name                  Type       location    Size
-----                 ------     ---------   -------
c webapi xx           folder     c:\test1    2 KB
c mvctutorial xx      folder     c:\test3    3 KB
done webapi xx        folder     c:\test1    11 KB
webapi done           folder     c:\test1    9 KB
webapi.zip            file       c:\test1    20 KB
mvc.iso               file       c:\test4    5 KB

i got a sample code which look like for finding files but the below code may not find folder. so i am looking for a sample code which will find files and folders too. so guide me to solve my issue.

the below sample code will find files but not sure does it find files by partial name. here is the code. i am not before dev environment. so could not test the below code.

find files code

static void Main(string[] args)
    {
        string partialName = "webapi";

        DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");
        FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");

        foreach (FileInfo foundFile in filesInDir)
        {
            string fullName = foundFile.FullName;
            Console.WriteLine(fullName);
        }

    }
like image 570
Mou Avatar asked Dec 06 '22 22:12

Mou


1 Answers

There is also a DirectoryInfo[] GetDirectories(string searchPattern) method in DirectoryInfo:

static void Main(string[] args)
{
    string partialName = "webapi";

    DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");
    FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");
    DirectoryInfo[] dirsInDir = hdDirectoryInWhichToSearch.GetDirectories("*" + partialName + "*.*");
    foreach (FileInfo foundFile in filesInDir)
    {
        string fullName = foundFile.FullName;
        Console.WriteLine(fullName);
    }
    foreach (DirectoryInfo foundDir in dirsInDir )
    {
        string fullName = foundDir.FullName;
        Console.WriteLine(fullName);
    }
}
like image 173
Bolu Avatar answered Dec 14 '22 23:12

Bolu