编码转换
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/* 在使用MySql时会遇到中文乱码的问题就此写下面两个函数
* 在写入数据库和从数据库读出时将编码改变
* author:alice
* date :2006/1/25
*/
//写入数据库时进行转换
public string GB2312_ISO8859(string write)
{
//声明字符集
System.Text.Encoding iso8859, gb2312;
//iso8859
iso8859 = System.Text.Encoding.GetEncoding("iso8859-1");
//国标2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] gb;
gb = gb2312.GetBytes(write);
//返回转换后的字符
return iso8859.GetString(gb);
}
//读出时进行转换
public string ISO8859_GB2312(string read)
{
//声明字符集
System.Text.Encoding iso8859, gb2312;
//iso8859
iso8859 = System.Text.Encoding.GetEncoding("iso8859-1");
//国标2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] iso;
iso = iso8859.GetBytes(read);
//返回转换后的字符
return gb2312.GetString(iso);
}
* 在写入数据库和从数据库读出时将编码改变
* author:alice
* date :2006/1/25
*/
//写入数据库时进行转换
public string GB2312_ISO8859(string write)
{
//声明字符集
System.Text.Encoding iso8859, gb2312;
//iso8859
iso8859 = System.Text.Encoding.GetEncoding("iso8859-1");
//国标2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] gb;
gb = gb2312.GetBytes(write);
//返回转换后的字符
return iso8859.GetString(gb);
}
//读出时进行转换
public string ISO8859_GB2312(string read)
{
//声明字符集
System.Text.Encoding iso8859, gb2312;
//iso8859
iso8859 = System.Text.Encoding.GetEncoding("iso8859-1");
//国标2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] iso;
iso = iso8859.GetBytes(read);
//返回转换后的字符
return gb2312.GetString(iso);
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//批量数据转换
//其实就是将dataset的内容读出到xml文件,然后再输出
public DataSet ISO8859_GB2312(DataSet ds)
{
string xml;
xml = ds.GetXml();
ds.Clear();
//声明字符集
System.Text.Encoding iso8859, gb2312;
//iso8859
iso8859 = System.Text.Encoding.GetEncoding("iso8859-1");
//国标2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] bt;
bt = iso8859.GetBytes(xml);
xml = gb2312.GetString(bt);
ds.ReadXml(new System.IO.StringReader(xml));
return ds;
}
//其实就是将dataset的内容读出到xml文件,然后再输出
public DataSet ISO8859_GB2312(DataSet ds)
{
string xml;
xml = ds.GetXml();
ds.Clear();
//声明字符集
System.Text.Encoding iso8859, gb2312;
//iso8859
iso8859 = System.Text.Encoding.GetEncoding("iso8859-1");
//国标2312
gb2312 = System.Text.Encoding.GetEncoding("gb2312");
byte[] bt;
bt = iso8859.GetBytes(xml);
xml = gb2312.GetString(bt);
ds.ReadXml(new System.IO.StringReader(xml));
return ds;
}
由于不同的操作系统对代码页支持不同,而Windows2000后,对于ASCII和Unicode都是内在支持的,所以它有这两个属性。对于其他字符集,要看你是否安装了,所以它提供了
System.Text.Encoding.GetEncoding(),来获取指定的字符集,我们的中文windows系统,就可以通过System.Text.Encoding.GetEncoding("GB2312")来得到中文字符集。当然你如果你要获取一个没装的字符集,他就要报错了。