说明

  通过ajax或者浏览上传文本文件,上传时候c#处理时候因为文本格式的创建不同,在获取内容时候会出现中文乱码。

解决方法

  通过上传的文件流,判断文件的编码格式,在使用对应的编码格式获取文本内容

  #region 通过给定的文件流,判断文件的编码类型
        /// <summary>
        /// 通过给定的文件流,判断文件的编码类型
        /// </summary>
        /// <param name=“fs“>文件流</param>
        /// <returns>文件的编码类型</returns>
        private string GetType(byte[] fs,out string errorMsg)
        {
            string reVal = "Default";
            errorMsg = "";
            if (IsUTF8Bytes(fs,out errorMsg) || (fs[0] == 0xEF && fs[1] == 0xBB && fs[2] == 0xBF))
            {
                reVal = "UTF8";
            }
            else if (fs[0] == 0xFE && fs[1] == 0xFF && fs[2] == 0x00)
            {
                reVal = "BigEndianUnicode";
            }
            else if (fs[0] == 0xFF && fs[1] == 0xFE && fs[2] == 0x41)
            {
                reVal = "Unicode";
            }
            return reVal;

        }
        #endregion

  //获取文本内容

  System.Text.Encoding.Default.GetString(fs)

测试结果

  Windows 平台下Default(默认格式),UTF8,BigEndianUnicode,Unicode大部分能识别到

posted on 2016-07-21 16:23  墨造梦人  阅读(5229)  评论(0编辑  收藏  举报