C# 文件简繁体转换
简繁体转换:
方案一:
准确性高,耗性能
方案二:
准确性低,效率高
1 using Microsoft.International.Converters.TraditionalChineseToSimplifiedConverter; 2 using System; 3 using System.Collections.Generic; 4 using System.IO; 5 using System.Linq; 6 using System.Text; 7 using System.Text.RegularExpressions; 8 9 namespace Simplified_Demo 10 { 11 class Program 12 { 13 static void Main(string[] args) 14 { 15 Regex regHtml = new Regex(@"[\u4e00-\u9fbb]+"); 16 17 var directoryStr = System.Configuration.ConfigurationManager.AppSettings["DirectoryStr"]; 18 var encodingStr = System.Configuration.ConfigurationManager.AppSettings["EncodingStr"]; 19 var filesPath = Directory.GetFiles(directoryStr, "*.*", SearchOption.AllDirectories); 20 int count = 0; 21 string strContent = string.Empty; 22 foreach (var filePath in filesPath) 23 { 24 //js,html,htm,aspx, 25 var ext = Path.GetExtension(filePath).ToLower(); 26 27 if (ext.EndsWith("js") || ext.EndsWith("html") || ext.EndsWith("htm") || ext.EndsWith("aspx") || ext.EndsWith("xml")) 28 { 29 if (File.Exists(filePath)) 30 { 31 try 32 { 33 if (string.IsNullOrEmpty(encodingStr)) 34 { 35 strContent = File.ReadAllText(filePath); 36 } 37 else 38 { 39 strContent = File.ReadAllText(filePath, Encoding.UTF8); 40 } 41 42 var matchs = regHtml.Matches(strContent); 43 if (matchs.Count == 0) continue; 44 45 foreach (Match m in matchs) 46 { 47 var txt = ChineseConverter.Convert(m.ToString(), ChineseConversionDirection.SimplifiedToTraditional); 48 strContent = Regex.Replace(strContent, m.ToString(), txt); 49 } 50 } 51 catch (Exception) 52 { 53 } 54 if (string.IsNullOrEmpty(encodingStr)) 55 { 56 File.WriteAllText(filePath, strContent); 57 } 58 else 59 { 60 File.WriteAllText(filePath, strContent, Encoding.UTF8); 61 } 62 } 63 64 Console.WriteLine(filesPath.Length); 65 Console.Write("|" + count++); 66 } 67 } 68 Console.WriteLine("OK"); 69 Console.ReadKey(); 70 } 71 } 72 }