1 class Program_Utf8
3 static void Main(string[] args)
5 String folderPath = @"E:\文件夹路径\";
7 ParseDirectory(folderPath, "*.cs", (filePath) =>
9 string text = "";
10 using (StreamReader read = new StreamReader(filePath, Encoding.Default))
11 {
12 string oldtext = read.ReadToEnd();
13 text = oldtext;
14 text = text.Replace("\n", "\r\n");
15 text = text.Replace("\r\r\n", "\r\n"); // 防止替换了正常的换行符
16 if (oldtext.Length == text.Length)
17 {
18 Console.WriteLine(filePath.Substring(filePath.LastIndexOf("\\") + 1) + " 不需要标准化");
19 return; // 如果没有变化就退出
20 }
21 }
22 File.WriteAllText(filePath, text, Encoding.UTF8); //utf-8格式保存,防止乱码
24 Console.WriteLine(filePath.Substring(filePath.LastIndexOf("\\") + 1) + " 行尾标准化完成");
25 });
27 Console.ReadKey();
28 }
30 /// <summary>递归所有的目录,根据过滤器找到文件,并使用委托来统一处理</summary>
31 /// <param name="info"></param>
32 /// <param name="filter"></param>
33 /// <param name="action"></param>
34 static void ParseDirectory(string folderPath, string filter, Action<string> action)
35 {
36 if (string.IsNullOrWhiteSpace(folderPath)
37 || folderPath.EndsWith("debug", StringComparison.OrdinalIgnoreCase)
38 || folderPath.EndsWith("obj", StringComparison.OrdinalIgnoreCase)
39 || folderPath.EndsWith("bin", StringComparison.OrdinalIgnoreCase))
40 return;
42 Console.WriteLine("读取目录:" + folderPath);
44 // 处理文件
45 string[] fileNameArray = Directory.GetFiles(folderPath, filter);
46 if (fileNameArray.Length > 0)
47 {
48 foreach (var filePath in fileNameArray)
49 {
50 action(filePath);
51 }
52 }
53 else
54 {
55 Console.WriteLine("未发现文件!");
56 }
58 Console.WriteLine("====================================");
60 //得到子目录,递归处理
61 string[] dirs = Directory.GetDirectories(folderPath);
62 var iter = dirs.GetEnumerator();
63 while (iter.MoveNext())
64 {
65 string str = (string)(iter.Current);
66 ParseDirectory(str, filter, action);
67 }
68 }
69 }