最近用到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 { //ioEx.Message } } public void Write() { string xml = "C#读写中文"; try{ string pathSource = "test.txt"; using (FileStream fsSource = new FileStream(pathSource, FileMode.Create,FileAccess.Write)) { //byte[] data = Encoding.Default.GetBytes(xml); byte[] data = UTF8Encoding.UTF8.GetBytes(xml); fsSource.Write(data, 0, data.Length); } } catch { // error } return; } }
解决unity3d读写中文乱码,布布扣,bubuko.com
原文:http://blog.csdn.net/mycwq/article/details/19813567