最近用到unity3d读写文件,遇到了中文乱码问题,就研究了一下。项目是C#写的,这里就介绍C#读写中文的例子。
首先,项目使用utf-8编码,文件也要utf-8编码
using System;
using System.IO;
using System.Text;
public class FileOp
{
public void Read()
{
try{
string pathSource = "test.txt";
using (FileStream fsSource = new FileStream(pathSource,
FileMode.Open, FileAccess.Read))
{
// Read the source file into a byte array.
byte[] bytes = new byte[fsSource.Length];
int numBytesToRead = (int)fsSource.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
numBytesToRead = bytes.Length;
//text = Encoding.Default.GetString(bytes);
text = UTF8Encoding.UTF8.GetString(bytes);
}
}
catch
{
//