如何按部分名称c#查找文件夹和文件

时间:2015-04-17 08:03:44

标签: c#

在我硬盘的特定文件夹中,我存储了许多其他子文件夹和文件。现在我想按部分名称列出这些文件夹和文件名。

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

现在,当我想通过部分名称 webapi 进行搜索时,我想获得具有webapi字词的文件和文件夹名称列表。我想在网格中显示他们的完整文件夹或文件名及其完整路径和大小。喜欢以下方式。

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

我有一个示例代码,看起来像查找文件,但下面的代码可能找不到文件夹。所以我正在寻找一个可以找到文件和文件夹的示例代码。所以引导我解决我的问题。

以下示例代码将查找文件但不确定是否按部分名称查找文件。这是代码。我不是在开发环境之前。所以无法测试下面的代码。

查找文件代码

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

    }

5 个答案:

答案 0 :(得分:5)

DirectoryInfo中还有一个DirectoryInfo[] GetDirectories(string searchPattern)方法:

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

答案 1 :(得分:3)

如果您只需要全名,可以使用更通用的类型“FileSystemInfo”。

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

修改 如果你需要特殊类型的方法,你仍然可以在每个循环中转换为:

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 :(得分:2)

正如其他人已声明使用DirectoryInfo.GetDirectoriesDirectoryInfo.GetFiles方法,但请记住使用SearchOptions.AllDirectories递归搜索子目录。

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

答案 3 :(得分:1)

使用递归函数here列出给定目录中所有文件的示例代码。只需使用string.Contains方法为这两个文件夹编写比较部分即可。和文件'名。

这是上面链接中给出的代码。

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

答案 4 :(得分:0)

我从一个答案示例代码中完成了完整的代码。所以我想发布完整的代码。

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