使用C#批量转换文本文件编码为UTF8

时间:2023-01-10 15:09:15

现在很多地方都要求程序源码用UTF8格式,因此需要将原来的源码转换一下,手动转显然太累了。

发现c#还真是简单啊,几行代码就搞定了。 试了一下GBK转换成UTF8编码格式,没什么问题了。 

static void Main(string[] args)
 {
     string dir, filters;
     Console.WriteLine("Please input the directory:");
     dir = Console.ReadLine();
     Console.WriteLine("Please input the filter(such as *.c,*.cpp):");
     filters = Console.ReadLine();
     Console.WriteLine("The following files will be converted:");
     List<string> destfiles = new List<string>();
     foreach (string filter in filters.Split(','))
     {
         foreach (var eachfileinfo in new DirectoryInfo(dir).GetFiles(filter, SearchOption.AllDirectories))
         {
             destfiles.Add(eachfileinfo.FullName);
             Console.WriteLine(eachfileinfo.FullName);
         }
     }
     Console.WriteLine("You Sure? (y or n)");
     string ans = Console.ReadLine();
     if (ans.Equals("y", StringComparison.OrdinalIgnoreCase))
     {
         foreach (string destfile in destfiles)
         {
             File.WriteAllText(destfile, File.ReadAllText(destfile,Encoding.Default), Encoding.UTF8);
         }
         Console.WriteLine("finished.");
     }
     else
     {
         Console.WriteLine("Nothing changed.");
     }
     Console.WriteLine("Press any key to exit.");
     Console.ReadLine();
 }