昨天在做一个背单词的软件,其中用了System.IO来读取单词文件。可是在用StreamReader sr = new StreamReader(FileName); 的时候,再输出sr.ReadLine();的时候,发现文件中的中文部分全都变成了乱码。于是我在网上找办法,最后终于找到了原因:
引用:(来自一剪梅)
究其原因,原来自从Windows 2000之后的操作系统在文件处理时默认编码采用Unicode,所以.Net 的文件默认编码也是Unicode。除非另外指定,StreamReader 的默认编码为 Unicode,而不是当前系统的 ANSI 代码页。但是文档大部分还是以ANSI编码储存,中文文本使用的是gb2312,所以才造成中文乱码的状况,也就是说在读取文本的时候要指定编码格式。
解决方法是System.Text.Encoding.Default 告诉
StreamReader 目前操作系统的编码即可。
StreamReader reader = new StreamReader(FileName, System.Text.Encoding.Default)
把文件转换成utf8编码
using System;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace WeiExcelToMysql
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//打开文件:(window的表格默认是gbk编码)
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
DialogResult dr = openFileDialog1.ShowDialog();
//获取所打开文件的文件名
string filename = openFileDialog1.FileName;
if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(filename))
{
StreamReader sr = new StreamReader(filename,System.Text.Encoding.Default); //以文件默认编码读取数据,同时转换成字符串
textBox1.Text = sr.ReadToEnd();
sr.Close();
}
}
//保存文件:(我们保存成utf-8编码)
private void button2_Click_1(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
DialogResult dr = saveFileDialog1.ShowDialog();
string filename = saveFileDialog1.FileName;
if (dr == System.Windows.Forms.DialogResult.OK && !string.IsNullOrEmpty(filename))
{
StreamWriter sw = new StreamWriter(filename, false, Encoding.UTF8); //true代表可以追加
sw.Write(textBox1.Text);
sw.Close();
}
}
}
}
编码字节流
using System;
using System.Text;
namespace WeiExcelToMysql
{
public class WeiGBK2UTF8
{
public static byte[] Get_utf8code(string gbkString)
{
//以windows默认的gbk编码读取字节流
byte[] gbkcode = System.Text.Encoding.Default.GetBytes(gbkString);
//关键也就是这句了:源,目标,字节串
byte[] utf8code = Encoding.Convert(System.Text.Encoding.Default, Encoding.UTF8, gbkcode);
//将utf8字节流转成字符串
UTF8Encoding utf8 = new UTF8Encoding();
String decodedString = utf8.GetString(utf8code);
return utf8code;
}
}
}