zoukankan      html  css  js  c++  java
  • C#文件上传编码乱码

    又遇到文件编码乱码的事情,这回稍微有些头绪,但是还是花了很多时间去解决。

    场景:上传csv文件,导入到数据库。上传文件的编码不定,需要转成unicode存储。

    问题点:需要解决判断上传文件的编码。

    关于编码,网上已有很多博客解释,只需查询关键字 unicode ansi bom 等

    下面贴一个.net 官方的一些编码类型 地址:https://msdn.microsoft.com/zh-cn/library/windows/desktop/dd317756(v=vs.85).aspx

    我这边主要是判断中文编码和unicode的一系列编码。在使用GB2312时发现该编码方式不存在,需要导入编码包:System.Text.Encoding.CodePages

    并在使用该编码前添加一行

    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

    之后即可使用,使用方式如下:

    Encoding.GetEncoding("GB2312")

    根据网上一个高分根据bom判断编码方式(GB2312无法根据bom判断,且我的案例中只需判断unicode和GB2312,因此修改了方法,default返回GB2312)

     1 /// <summary>
     2         /// 获取文件编码方式
     3         /// </summary>
     4         /// <param name="filename"></param>
     5         /// <returns></returns>
     6         public static Encoding GetEncoding(string filename)
     7         {
     8             // Read the BOM
     9             var bom = new byte[4];
    10             using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
    11             {
    12                 file.Read(bom, 0, 4);
    13             }
    14 
    15             // Analyze the BOM
    16             if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
    17             if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
    18             if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
    19             if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
    20             if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return Encoding.UTF32;
    21             return Encoding.GetEncoding("GB2312");
    22         }

    另外,在上传的文件是根据这个编码方式,读入文件流,而.net内部本身就是unicode编码,可以直接存储使用。

    1  var encoding = GetEncoding(filePath);
    2  using (var sr = new StreamReader(file.OpenReadStream(), encoding, true)) //此处必须设置为true,用于设置自动察觉bom
    3  {
    4      using (var sw = new StreamWriter(filePath))
    5      {
    6           await sw.WriteAsync(sr.ReadToEnd()).ConfigureAwait(false);
    7      }
    8  }

    关于这个自动察觉bom,借鉴博客https://www.mgenware.com/blog/?p=175

  • 相关阅读:
    病毒写法,资源的释放.
    MinHook库的使用 64位下,过滤LoadLibraryExW
    系统权限远程线程注入到Explorer.exe
    【Unity】4.5 树木创建器
    【Unity】4.4 添加角色控制器
    【Unity】4.3 地形编辑器
    【Unity】4.2 提升开发效率的捷径--导入 Unity 5.3.4 自带的资源包
    【Unity】4.1 创建组件
    【Unity】4.0 第4章 创建基本的游戏场景
    【Unity】3.6 导入图片资源
  • 原文地址:https://www.cnblogs.com/sylvialucy/p/9182332.html
Copyright © 2011-2022 走看看