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

I have saved many other subfolders and files in a specific folder on my hard drive. now I want to list the names of these folders and files 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 that i like to search by private webapi name then i want to get a list of file and folder names named webapi. I want to show the full folder or file name in the grid with their full path and size. like below.

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 have some sample code that is similar to searching for files, but the code below may not find the folder. so I'm looking for some sample code that will find files and folders as well. so help me solve my problem.

the below example code will find files but not sure if it will find files by private name. here is the code. I'm not up to the Dev environment. so failed to verify the below code.

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

    }

      

+3


source to share


5 answers


You can use the more general FileSystemInfo type if you just need the fully qualified 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 want methods of specialized types that you can still use 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();
    }
}

      

+2


source


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

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

      

+4


source


As others have stated, use the DirectoryInfo.GetDirectories

and methods DirectoryInfo.GetFiles

, but remember to use it SearchOptions.AllDirectories

to recursively find subdirectories.

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)
{
    //
}

      

+2


source


Here is some sample code to list all files in a given directory using recursive functions here . Just write the comparative part using string.Contains for folder and file 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);       
    }
}

      

+1


source


I will complete the complete code taken from one of the response code examples. so here I like to post the complete 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
                );
        }
    }
}

      

0


source







All Articles