本帖最后由 Gin_Q 于 2021-3-2 19:47 编辑
回复 2# slimay
遍历整个目录!是真的快!- using System;
- using System.Text;
- using System.IO;
-
- class FindFileByExtension
- {
- static void Main(string[] args)
- {
- // Console.WriteLine(args.Length);
-
- // 所有文件信息储存文件 utf-8
- string log = @"D:\GIN\c#\Exercise\log.csv";
-
- // 创建一个指定编码的空文件
- StreamWriter Log = new StreamWriter(log, false, Encoding.GetEncoding("GB2312"));
-
- string startFolder = @"D:\";
-
- // 指定不可访问的目录
- string[] skipList = {@"$RECYCLE.BIN", @"System Volume Information"};
-
- DirectoryInfo dir = new DirectoryInfo(startFolder);
-
- int count = 0;
- foreach (var each in dir.GetDirectories())
- {
- // 查询是否包含不可访问目录
- if (each.FullName.Contains(skipList[0]) || each.FullName.Contains(skipList[1]))
- {
- Console.WriteLine("跳过指定目录:{0}",each.FullName);
- continue;
- }
-
- DirectoryInfo eachDir = new DirectoryInfo(each.FullName);
- // 在搜索操作中包括当前目录和所有它的子目录。 此选项在搜索中包括重解析点,比如安装的驱动器和符号链接。
- foreach (System.IO.FileInfo fi in eachDir.GetFiles("*.*", System.IO.SearchOption.AllDirectories))
- {
- count++;
- // Console.WriteLine("{0},{1},{2}",count, fi.FullName, fi.Length);
- Log.WriteLine(CodeConvert(String.Format("{0},{1},{2}",count, fi.FullName, fi.Length), "utf-8", "GB2312"));
- // Log.WriteLine("{0},{1},{2}",count, fi.FullName, fi.Length);
- }
- }
- }
-
- static string CodeConvert(string str, string srcCoding, string desCoding)
- {
- // 将字符串按指定编码,解码成字节数组
- byte[] barr = Encoding.GetEncoding(srcCoding).GetBytes(str);
- // 将解码好的字节数组,按原编码转换为指定编码的字节数组;
- barr = Encoding.Convert(Encoding.GetEncoding(srcCoding), Encoding.GetEncoding(desCoding), barr);
- // 将转换好的字节数组,按指定编码,解码为字符串!
- return Encoding.GetEncoding(desCoding).GetString(barr);
- }
- }
复制代码
|