这个函数通过判断Stream头字节来判断并返回Unicode或GBK(兼容Ascii,用于中文)编码。 string GetTextFromFile(string path) { FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); Encoding enc; if (fs.CanSeek) { byte[] bom = new byte[4]; // Get the byte-order , if there is one fs.Read(bom, 0, 4); if ((bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) || // utf-8 (bom[0] == 0xff && bom[1] == 0xfe) || // ucs-2le, ucs-4le, and ucs-16le (bom[0] == 0xfe && bom[1] == 0xff) || // utf-16 and ucs-2 (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)) // ucs-4 { enc = System.Text.Encoding.Unicode; } else { enc = System.Text.Encoding.GetEncoding("GBK"); } // Now reposition the file cursor back to the start of the file fs.Seek(0, System.IO.SeekOrigin.Begin); } else { enc = System.Text.Encoding.GetEncoding("GBK"); } return File.ReadAllText(path, enc); }
ansic,又能通用utf8这两个很难通用,很难。想别的法吧,不要一条路使劲走。
//-------------为文件创建一个流 FileInfo fi = new FileInfo(@"D:\123424.txt"); FileStream f = fi.Create(); //-------------编码 StreamWriter sw = new StreamWriter(f, Encoding.GetEncoding("gb2312")); sw.WriteLine(//你要输入的文本); sw.Close(); //读取 StreamReader sr = new StreamReader(@"d:\123424.txt", Encoding.GetEncoding("gb2312")); //你要显示的文本= sr.ReadToEnd(); sr.Close();
string GetTextFromFile(string path)
{
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read); Encoding enc;
if (fs.CanSeek)
{
byte[] bom = new byte[4]; // Get the byte-order , if there is one
fs.Read(bom, 0, 4);
if ((bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) || // utf-8
(bom[0] == 0xff && bom[1] == 0xfe) || // ucs-2le, ucs-4le, and ucs-16le
(bom[0] == 0xfe && bom[1] == 0xff) || // utf-16 and ucs-2
(bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff)) // ucs-4
{
enc = System.Text.Encoding.Unicode;
}
else
{
enc = System.Text.Encoding.GetEncoding("GBK");
}
// Now reposition the file cursor back to the start of the file
fs.Seek(0, System.IO.SeekOrigin.Begin);
}
else
{
enc = System.Text.Encoding.GetEncoding("GBK");
} return File.ReadAllText(path, enc); }
//-------------为文件创建一个流
FileInfo fi = new FileInfo(@"D:\123424.txt");
FileStream f = fi.Create();
//-------------编码
StreamWriter sw = new StreamWriter(f, Encoding.GetEncoding("gb2312"));
sw.WriteLine(//你要输入的文本);
sw.Close();
//读取
StreamReader sr = new StreamReader(@"d:\123424.txt", Encoding.GetEncoding("gb2312"));
//你要显示的文本= sr.ReadToEnd();
sr.Close();