ToB企服应用市场:ToB评测及商务社交产业平台

标题: .net6下使用DotnetZip解压文件,中文出现乱码问题解决 [打印本页]

作者: 铁佛    时间: 2022-9-17 08:38
标题: .net6下使用DotnetZip解压文件,中文出现乱码问题解决
DotnetZip使用方法见此文章
https://www.cnblogs.com/pengze0902/p/6124659.html

在netframework环境下,使用上面文章中的设置Encoding为Default的方法即可解决中文乱码问题



 
但是当我使用.net6创建控制台项目并采用上述代码时,发现中文乱码问题并未得到解决。
经过整合搜索内容,发现在.netcore中若想使中文不发生乱码,需要进行如下配置
1.
  1. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
复制代码
 2.
  1. System.Text.Encoding.GetEncoding("gbk")
复制代码
  1. 1 /// <summary>
  2. 2         /// 解压ZIP文件
  3. 3         /// </summary>
  4. 4         /// <param name="strZipPath">待解压的ZIP文件</param>
  5. 5         /// <param name="strUnZipPath">解压的目录</param>
  6. 6         /// <param name="overWrite">是否覆盖</param>
  7. 7         /// <returns>成功:true/失败:false</returns>
  8. 8         public static bool Decompression(string strZipPath, string strUnZipPath, bool overWrite)
  9. 9         {
  10. 10             if (string.IsNullOrEmpty(strZipPath))
  11. 11             {
  12. 12                 throw new ArgumentNullException(strZipPath);
  13. 13             }
  14. 14             if (string.IsNullOrEmpty(strUnZipPath))
  15. 15             {
  16. 16                 throw new ArgumentNullException(strUnZipPath);
  17. 17             }
  18. 18             try
  19. 19             {
  20. 20                 var options = new ReadOptions
  21. 21                 {
  22. 22                     //设置编码,解决解压文件时中文乱码
  23. 23                     Encoding = System.Text.Encoding.GetEncoding("gbk")
  24. 24                 };
  25. 25                 using (var zip = ZipFile.Read(strZipPath, options))
  26. 26                 {
  27. 27                     foreach (var entry in zip)
  28. 28                     {
  29. 29                         if (string.IsNullOrEmpty(strUnZipPath))
  30. 30                         {
  31. 31                             strUnZipPath = strZipPath.Split('.').First();
  32. 32                         }
  33. 33                         entry.Extract(strUnZipPath, overWrite
  34. 34                                 ? ExtractExistingFileAction.OverwriteSilently
  35. 35                                 : ExtractExistingFileAction.DoNotOverwrite);
  36. 36                     }
  37. 37                     return true;
  38. 38                 }
  39. 39             }
  40. 40             catch (Exception ex)
  41. 41             {
  42. 42                 throw new Exception(ex.Message);
  43. 43             }
  44. 44         }
复制代码
 
 
 注:framework程序中使用Encoding.Default即可解决中文乱码问题
但在.netcore中需要使用Encoding.GetEncoding("gbk")解决中文乱码问题

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4