Mou
Mou

Reputation: 16282

How to find folders and files by its partial name 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);
        }

    }

Upvotes: 6

Views: 29343

Answers (5)

Mou
Mou

Reputation: 16282

i complete the full code taking from one of the answer sample code. so here i like to post the full code.

namespace PatternSearch
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private long GetDirectorySize(string folderPath)
        {
            DirectoryInfo di = new DirectoryInfo(folderPath);
            return di.EnumerateFiles("*.*", SearchOption.AllDirectories).Sum(fi => fi.Length);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            List<FileList> oLst = new List<FileList>();

            string partialName = "webapi";

            DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"C:\MyFolder");
            FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" + partialName + "*");

            foreach (FileSystemInfo foundFile in filesAndDirs)
            {
                string fullName = foundFile.FullName;
                Console.WriteLine(fullName);

                if (foundFile.GetType() == typeof(FileInfo))
                {
                    FileInfo fileInfo = (FileInfo)foundFile;
                    oLst.Add(new FileList
                    {
                        Name = fileInfo.Name,
                        Type = "File",
                        location = fileInfo.FullName,
                        Size = Format.ByteSize(fileInfo.Length)
                    });
                }

                if (foundFile.GetType() == typeof(DirectoryInfo))
                {
                    Console.WriteLine("... is a directory");
                    DirectoryInfo directoryInfo = (DirectoryInfo)foundFile;
                    FileInfo[] subfileInfos = directoryInfo.GetFiles();
                    oLst.Add(new FileList
                    {
                        Name = directoryInfo.Name,
                        Type = "Folder",
                        location = directoryInfo.FullName,
                        Size = Format.ByteSize(GetDirectorySize(directoryInfo.FullName))
                    });
                }
            }
            dataGridView1.DataSource = oLst;
        }
    }

    public class FileList
    {
        public string Name { get; set; }
        public string Type { get; set; }
        public string location { get; set; }
        public string Size { get; set; }
    }

    public static class Format
    {
        static string[] sizeSuffixes = { "B", "KB", "MB", "GB", "TB" };

        public static string ByteSize(long size)
        {
            string SizeText = string.Empty;
            const string formatTemplate = "{0}{1:0.#} {2}";

            if (size == 0)
            {
                return string.Format(formatTemplate, null, 0, "Bytes");
            }

            var absSize = Math.Abs((double)size);
            var fpPower = Math.Log(absSize, 1000);
            var intPower = (int)fpPower;
            var iUnit = intPower >= sizeSuffixes.Length
                ? sizeSuffixes.Length - 1
                : intPower;
            var normSize = absSize / Math.Pow(1000, iUnit);

            switch (sizeSuffixes[iUnit])
            {
                case "B":
                    SizeText= "Bytes";
                    break;
                case "KB":
                    SizeText = "Kilo Bytes";
                    break;
                case "MB":
                    SizeText = "Mega Bytes";
                    break;
                case "GB":
                    SizeText = "Giga Bytes";
                    break;
                case "TB":
                    SizeText = "Tera Bytes";
                    break;
                default:
                    SizeText = "None";
                    break;
            }

            return string.Format(
                formatTemplate,
                size < 0 ? "-" : null, normSize, SizeText
                );
        }
    }
}

Upvotes: 0

JanTheGun
JanTheGun

Reputation: 2213

You can use the more general type "FileSystemInfo" if you just need the full name.

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

    DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");
     FileSystemInfo[] filesAndDirs = hdDirectoryInWhichToSearch.GetFileSystemInfos("*" + partialName + "*");

    foreach (FileSystemInfo foundFile in filesAndDirs)
    {
        string fullName = foundFile.FullName;
        Console.WriteLine(fullName);
    }
}

Edit: If you need the methods of the specialized types you still can cast to that in the for each loop:

foreach (FileSystemInfo foundFile in filesAndDirs)
{
    string fullName = foundFile.FullName;
    Console.WriteLine(fullName);

    if (foundFile.GetType() == typeof(FileInfo))
    {
        Console.WriteLine("... is a file");
        FileInfo fileInfo = (FileInfo)foundFile;
        Console.WriteLine("Extension: " + fileInfo.Extension);
    }

    if (foundFile.GetType() == typeof(DirectoryInfo))
    {
        Console.WriteLine("... is a directory");
        DirectoryInfo directoryInfo = (DirectoryInfo)foundFile;
        FileInfo[] subfileInfos = directoryInfo.GetFiles();
    }
}

Upvotes: 4

transporter_room_3
transporter_room_3

Reputation: 2633

As others have stated use DirectoryInfo.GetDirectories and DirectoryInfo.GetFiles methods, but remember to use SearchOptions.AllDirectories to recursively search subdirectories as well.

try
{
    const string searchQuery = "*" + "keyword" + "*";
    const string folderName = @"C:\Folder";

    var directory = new DirectoryInfo(folderName);

    var directories = directory.GetDirectories(searchQuery, SearchOption.AllDirectories);
    var files = directory.GetFiles(searchQuery, SearchOption.AllDirectories);

    foreach (var d in directories)
    {
        Console.WriteLine(d);
    }

    foreach (var f in files)
    {
        Console.WriteLine(f);
    }
}
catch (Exception e)
{
    //
}

Upvotes: 3

Bhaskar
Bhaskar

Reputation: 1036

There's an example code to list all the files in a given directory using recursive functions here. Just write the comparison part using string.Contains method for both the folders' and files' names.

This is the code given in the above link.

// For Directory.GetFiles and Directory.GetDirectories 
// For File.Exists, Directory.Exists 
using System;
using System.IO;
using System.Collections;

public class RecursiveFileProcessor 
{
    public static void Main(string[] args) 
    {
        foreach(string path in args) 
        {
            if(File.Exists(path)) 
            {
                // This path is a file
                ProcessFile(path); 
            }               
            else if(Directory.Exists(path)) 
            {
                // This path is a directory
                ProcessDirectory(path);
            }
            else 
            {
                Console.WriteLine("{0} is not a valid file or directory.", path);
            }        
        }        
    }


    // Process all files in the directory passed in, recurse on any directories  
    // that are found, and process the files they contain. 
    public static void ProcessDirectory(string targetDirectory) 
    {
        // Process the list of files found in the directory. 
        string [] fileEntries = Directory.GetFiles(targetDirectory);
        foreach(string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory. 
        string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach(string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    // Insert logic for processing found files here. 
    public static void ProcessFile(string path) 
    {
        Console.WriteLine("Processed file '{0}'.", path);       
    }
}

Upvotes: 1

Bolu
Bolu

Reputation: 8786

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

Upvotes: 8

Related Questions