1- // See https://aka.ms/new-console-template for more information
2- Console . WriteLine ( "Hello, World!" ) ;
1+ using System . Diagnostics ;
2+ using System . Text ;
3+ using ShellProgressBar ;
4+
5+ namespace TraverseFolderEncoded ;
6+
7+ internal abstract class Program
8+ {
9+ static async Task Main ( string [ ] args )
10+ {
11+ Console . WriteLine ( "Welcome to use TraverseFolderEncoded!" ) ;
12+ if ( args . Length != 2 )
13+ {
14+ Console . WriteLine ( "Incorrect startup parameters." ) ;
15+ Console . WriteLine ( "Example: TraverseFolderEncoded.exe [Encoded(utf-8/gbk/gb2312/65001...)] [File/Folder Path]" ) ;
16+ Console . Write ( "Press any key to exit..." ) ;
17+ Console . ReadKey ( ) ;
18+ }
19+ else
20+ {
21+ string folderPath = args [ 1 ] ; // 指定文件夹路径
22+ string targetEncodingStringName = args [ 0 ] ; // 指定目标编码名称
23+ int . TryParse ( args [ 0 ] , out var targetEncodingIntName ) ;
24+ Encoding . RegisterProvider ( CodePagesEncodingProvider . Instance ) ;
25+ // 获取文件夹中的所有文件
26+ string [ ] files = Directory . GetFiles ( folderPath , "*" , SearchOption . AllDirectories ) ;
27+
28+ Encoding targetEncoding ;
29+ if ( targetEncodingIntName != 0 )
30+ targetEncoding = Encoding . GetEncoding ( targetEncodingIntName ) ;
31+ else
32+ targetEncoding = Encoding . GetEncoding ( targetEncodingStringName ) ;
33+ int totalTicks = files . Length ;
34+ var options = new ProgressBarOptions
35+ {
36+ // 设置前景色
37+ ForegroundColor = ConsoleColor . Yellow ,
38+ // 设置完成时的前景色
39+ ForegroundColorDone = ConsoleColor . DarkGreen ,
40+ // 设置背景色
41+ BackgroundColor = ConsoleColor . DarkGray ,
42+ // 设置背景字符
43+ BackgroundCharacter = '\u2593 '
44+ } ;
45+ Stopwatch stopwatch = new Stopwatch ( ) ;
46+ using ( var pbar = new ProgressBar ( totalTicks , "Processing" , options ) )
47+ {
48+ //double percent = 100.00 / files.Length;
49+ stopwatch . Start ( ) ;
50+ // 遍历所有文件并修改编码
51+ foreach ( string file in files )
52+ {
53+ pbar . Message = $ "Start { Array . IndexOf ( files , file ) + 1 } of { files . Length } : { file } ";
54+ // 读取文件内容
55+ byte [ ] bytes = File . ReadAllBytes ( file ) ;
56+ // 将文件内容从原编码转换为目标编码
57+ Encoding sourceEncoding = Encoding . Default ; // 自动检测原编码
58+ byte [ ] targetBytes = Encoding . Convert ( sourceEncoding , targetEncoding , bytes ) ;
59+ await Task . Delay ( 1 ) ;
60+ // 将转换后的内容写入文件
61+ File . WriteAllBytes ( file , targetBytes ) ;
62+ pbar . Tick ( $ "End { Array . IndexOf ( files , file ) + 1 } of { files . Length } : { file } ") ;
63+ }
64+ stopwatch . Stop ( ) ;
65+ }
66+
67+ Console . WriteLine ( "All files have been converted to {0} encoding, taking time {1}" ,
68+ targetEncoding . EncodingName , stopwatch . Elapsed ) ;
69+ Console . Write ( "Press any key to exit..." ) ;
70+ Console . ReadKey ( ) ;
71+ }
72+ }
73+ }
0 commit comments