Blog / 阅读

解决unity3d读写中文乱码

by admin on 2014-03-29 11:04:49 in ,



最近用到unity3d读写文件,遇到了中文乱码问题,就研究了一下。项目是C#写的,这里就介绍C#读写中文的例子。


首先,项目使用utf-8编码,文件也要utf-8编码


[csharp] view plaincopy
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;  
    }  
}  



写评论

相关文章

上一篇:C#删除字符串最后一个字符的几种方法

下一篇:DES加密算法详解- -

评论

写评论

* 必填.

分享

栏目

赞助商


热门文章

Tag 云