6

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

    }
Mou
  • 15,673
  • 43
  • 156
  • 275
  • 2
    If you search for "webapi", why should `mvc.iso` appear in the list? – Lasse V. Karlsen Apr 17 '15 at 08:10
  • 1
    I'd say it's not very polite to use other people's time with a coding question when you haven't even tried anything yourself ("i am not before dev environment. so could not test the below code."). – nodots Apr 17 '15 at 08:26
  • possible duplicate of [How to search file with pattern](http://stackoverflow.com/questions/20704664/how-to-search-file-with-pattern) – Xaruth Apr 17 '15 at 08:48
  • @ Xaruth : wrong post url. please read my problem and give solution in c# not in other language. – Mou Apr 17 '15 at 08:50
  • @ Lasse V. Karlsen : yes mvc.iso should not come. that was my mistake in post. – Mou Apr 17 '15 at 08:51
  • thanks all for sharing all your sample code and i will let all u know if the below code sample help me to solve the issue. thanks – Mou Apr 17 '15 at 08:53
  • @Xaruth how can a question about PHP be a possible duplicate of a question about C#?? – tom redfern Apr 17 '15 at 09:35
  • @TomRedfern & Mou something wrong, that was not the link i wanted to post. – Xaruth Apr 17 '15 at 09:47
  • See this post, it'll be useful for you : http://stackoverflow.com/questions/2106877/is-there-a-faster-way-than-this-to-find-all-the-files-in-a-directory-and-all-sub/ – Xaruth Apr 17 '15 at 09:54

5 Answers5

8

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);
    }
}
Bolu
  • 8,696
  • 4
  • 38
  • 70
4

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();
    }
}
JanTheGun
  • 2,165
  • 17
  • 25
3

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)
{
    //
}
transporter_room_3
  • 2,583
  • 4
  • 33
  • 51
1

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);       
    }
}
Bhaskar
  • 1,028
  • 12
  • 16
0

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
                );
        }
    }
}
Mou
  • 15,673
  • 43
  • 156
  • 275