C# 两种实现编码转换的方法 - 小众知识

C# 两种实现编码转换的方法

2014-07-23 12:18:32 苏内容
  标签: C//编码
阅读:4502

第一种使用C#自己的方法Encoding:

public string convEncode(string write,string fromEncode,string toEncode) 
{ 
            //声明字符集 
            Encoding From,To;
            From = Encoding.GetEncoding(fromEncode);             
            To = Encoding.GetEncoding(toEncode); 
            byte[] temp = From.GetBytes(write); 
            byte[] temp1 = Encoding.Convert(From,To,temp);        
            //返回转换后的字符 
            return   To.GetString(temp1);
}


第二种调用C++的MultiByteToWideChar方法,即

[DllImport("kernel32.dll")]
public static extern int MultiByteToWideChar ( int CodePage, int dwFlags,string lpMultiByteStr,
                   int cchMultiByte, [MarshalAs(UnmanagedType.LPWStr)]string lpWideCharStr, int cchWideChar);

public string MByteToWChar(string content,int toEncode) 
{ 
            //字符编码转换 gb2312:936   utf-8:65001  big5:950  latin1:1252
            int len = pInvoke.MultiByteToWideChar(toEncode,0,content,-1,null,0);
            char[] temp = new char[len];
            string content1 = new string(temp);
            pInvoke.MultiByteToWideChar(toEncode,0,content,-1,content1,len);  
            return  content1;
}
扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1