c#如何实现搜索文件?

济南云服务器 2025年6月27日05:16:12C#教程c#如何实现搜索文件?已关闭评论51阅读模式

在开发一些软件时,需要我们遍历系统中是否存在某个文件,那么,我们如何通过c#编程语言快速搜索系统中某个文件呢?

关键代码:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("请输入要搜索的文件或目录:");
        string path = Console.ReadLine(); // 用户输入路径
        Console.WriteLine("请输入要搜索的文件名模式(例如 *.txt):");
        string searchPattern = Console.ReadLine(); // 用户输入搜索模式

        try
        {
            // 获取所有匹配的文件路径
            string[] files = Directory.GetFiles(path, searchPattern, SearchOption.AllDirectories);
            foreach (var file in files)
            {
                FileInfo fileInfo = new FileInfo(file);
                // 输出文件完整路径
                Console.WriteLine(fileInfo.FullName);
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            // 处理无权限访问的情况
            Console.WriteLine("访问被拒绝:" + ex.Message);
        }
        catch (DirectoryNotFoundException ex)
        {
            // 处理未找到目录的情况
            Console.WriteLine("目录未找到:" + ex.Message);
        }
        catch (Exception ex)
        {
            // 处理其他异常
            Console.WriteLine("发生错误:" + ex.Message);
        }
    }
}

济南云服务器
  • 本文由 发表于 2025年6月27日05:16:12
  • 转载请务必保留本文链接:http://news.hcsw666.com/2116