用Unicode编码方式读取文件

来源:互联网 发布:java抽象类构成 编辑:程序博客网 时间:2024/06/06 07:51

        最近的项目开发要使用日文,因此需要一款能同时编辑中文和日文的小编辑软件。很不幸,我一直青睐的UE不具备这样的功能。就打算自己写一个。其实要让自己的编辑器支持多种语言不是一件困难的事。就一个编码的问题。在MSDN上查了一下,直到Unicode是一种可以支持任何语言的编码方式。所以,只要在读取文件的时候指定Unicode编码方式就可以了。提供两种方式:

        一是用File.OpenText(string strFilePath)。OpenText返回一个StreamReader,并制定编码方式为UTF-8:

        private string ReadUnicodeByFile(string strFilePath)
        
{
            
//OpenText默认的编码方式就是UTF-8。
            StreamReader sr = File.OpenText(strFilePath);

            
string strFileContext = sr.ReadToEnd();

            sr.Close();

            
return strFileContext;
        }

        二是仍然用StreamReader,指定编码方式为Unicode:

        private string ReadUnicodeByStream(string strFilePath)
        
{
            
//用流的方式读取文件的时候指定编码方式
            StreamReader sr = new StreamReader(strFilePath, new UnicodeEncoding());

            
string strFileContext = sr.ReadToEnd();

            sr.Close();

            
return strFileContext;
        }

        上面的两种方式可用来读取任何语言的文件。