C# compare different Encoding pattern between UTF8 and UTF32 based on Md5
1 using System; 2 using System.Text; 3 using System.IO; 4 using System.Security.Cryptography; 5 6 static void Main(string[] args) 7 { 8 CompareFileGetBytes("lyf.txt"); 9 Console.ReadLine(); 10 } 11 12 static void CompareFileGetBytes(string fileFullName) 13 { 14 byte[] fileReadAllBytes = File.ReadAllBytes(fileFullName); 15 string fileReadAllBytesMd5 = GetBytesMd5(fileReadAllBytes); 16 17 string utf8Md5 = string.Empty; 18 using (StreamReader reader = new StreamReader(fileFullName)) 19 { 20 string textResult = reader.ReadToEnd(); 21 byte[] utf8Bytes = Encoding.UTF8.GetBytes(textResult); 22 utf8Md5 = GetBytesMd5(utf8Bytes); 23 } 24 25 string utf32Md5 = string.Empty; 26 using (StreamReader utf32Reader = new StreamReader(fileFullName)) 27 { 28 string textResult = utf32Reader.ReadToEnd(); 29 byte[] utf32Bytes = Encoding.UTF32.GetBytes(textResult); 30 utf32Md5 = GetBytesMd5(utf32Bytes); 31 } 32 33 34 Console.WriteLine($"fileReadAllBytesMd5:{fileReadAllBytesMd5},utf8Md5:{utf8Md5}"); 35 36 if (string.Equals(fileReadAllBytesMd5, utf8Md5)) 37 { 38 Console.WriteLine($"{nameof(fileReadAllBytesMd5)} is equal with {nameof(utf8Md5)}!"); 39 } 40 else 41 { 42 Console.WriteLine($"{nameof(fileReadAllBytesMd5)} is not equal with {nameof(utf8Md5)}!"); 43 } 44 45 Console.WriteLine($"utf8Md5:{utf8Md5},utf32Md5:{utf32Md5}"); 46 if (string.Equals(utf8Md5, utf32Md5)) 47 { 48 Console.WriteLine($"{nameof(utf8Md5)} is equals with {nameof(utf32Md5)}"); 49 } 50 else 51 { 52 Console.WriteLine($"{nameof(utf8Md5)} is not equals with {nameof(utf32Md5)}"); 53 } 54 } 55 56 static string GetBytesMd5(byte[] bytesData) 57 { 58 StringBuilder md5Builder = new StringBuilder(); 59 using(MD5CryptoServiceProvider md5=new MD5CryptoServiceProvider()) 60 { 61 byte[] md5Bytes = md5.ComputeHash(bytesData); 62 for(int i=0;i<md5Bytes.Length;i++) 63 { 64 md5Builder.Append(md5Bytes[i].ToString("x2")); 65 } 66 } 67 return md5Builder.ToString(); 68 }
I had validated that different encoding mode can generate different result,they are not identical.
Besides,the File.ReadAllBytes may based on UTF8 because they render the identical result!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现