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


第一种使用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;
}