文件的深度搜索和广度搜索
1: using System;
2: using System.Collections.Generic;
3: using System.Linq;
4: using System.Text;
5: using System.IO;
6: using System.Collections;
7:
8: namespace ListFiles
9: { 10: class Program
11: { 12: static private void GetChildFiles(DirectoryInfo childDir,string strExtension,ArrayList files)//递归扫描每一个文件和文件夹
13: //chidDir 子目录列表 strExtension 扩展名 files 文件数组
14: { 15: FileInfo [] file = childDir.GetFiles(); //获取子目录的所有文件
16: foreach (FileInfo ss in file) //获取子目录文件中有相应扩展名的文件
17: { 18: if(ss.Extension == strExtension )
19: files.Add(ss);
20: }
21: // 递归进入每一个子目录
22: DirectoryInfo[] kk = childDir.GetDirectories(); //获取当前目录的子目录
23: foreach (DirectoryInfo ww in kk)
24: { 25: GetChildFiles(ww, strExtension, files);
26: }
27: }
28:
29: private ArrayList GetAllFiles(string strPath,string strExtension)
30: //strPath目录,strExtension 扩展名
31: { 32: ArrayList files = new ArrayList();
33: DirectoryInfo dir=new DirectoryInfo(strPath);
34: FileInfo[] result=dir.GetFiles(); //获得该目录所以文件存入result[]数组中去
35:
36: foreach (FileInfo file in result ) //检索相应扩展名的文件
37: { 38: if(file.Extension == strExtension)
39: files.Add(file); //如果是要寻找的扩展名添加到文件数组中去
40: }
41: DirectoryInfo[] childDir = dir.GetDirectories(); //获取当前目录的子目录
42: foreach(DirectoryInfo file in childDir )
43: { 44: GetChildFiles(file,strExtension,files);
45: }
46: return files;
47: }
48:
49: static void Main(string[] args)
50: { 51: Program test = new Program();
52: Console.WriteLine("请输入指定目录名: "); 53: string dir = Console.ReadLine();
54: Console.WriteLine("请输入指定扩展名: "); 55: string extension = Console.ReadLine();
56: ArrayList files = new ArrayList(); //建立文件数组
57: files = test.GetAllFiles(dir, extension);
58: if (files.Count == 0) //获取文件数组中的文件数
59: Console.WriteLine("\n该目录下无以 " + extension + " 为扩展名的文件"); 60: else
61: { 62: Console.WriteLine("\n该目录下以{0}为扩展名的文件及父目录,创建时间,上次修改时间,文件长度等属性如下:\n", extension); 63: foreach (FileInfo file in files)
64: { 65: Console.WriteLine(file.Name + " " + file.Directory.Name + " " + file.CreationTime + " " + file.LastWriteTime + " " + file.Length);
66: }
67: }
68: Console.ReadKey();
69: }
70: }
71: }
TAG: