日期:2014-05-18  浏览次数:20985 次

FileInfo.CreateText()编码问题
用下面的代码写入文件编码为:ansi
C# code

            FileInfo fi = new FileInfo(FILE_NAME);
            if (!fi.Exists)
            {
                using (StreamWriter sw = fi.CreateText())
                {
                    sw.WriteLine("hello word");
                    sw.Close();

                }
            }



用下面的代码写入文件编码为:utf-8
C# code

            using (StreamWriter sw = new StreamWriter(FILE_NAME, true, Encoding.UTF8))
            {
                sw.WriteLine("hello word");
                sw.Close();

            }



如何通过FileInfo来实现UTF-8编码? CreateText()并无重载。

如何先 FileInfo.Create()。然后再 new StreamWriter(FILE_NAME, true, Encoding.UTF8))。文件会是独占状态。


------解决方案--------------------
C# code

using System;
using System.IO;
using System.Text;
class Test 
{
    public static void Main() 
    {
         string path = @"c: test.txt";
         FileInfo fi = new FileInfo(path);
        // Delete the file if it exists.
        if (fi.Exists) 
        {
             fi.Delete();
         }
        //Create the file.
        using (FileStream fs = fi.Create()) 
        {
             Byte[] info = 
                new UTF8Encoding(true).GetBytes("This is some text in the file.");
            //Add some information to the file.
             fs.Write(info, 0, info.Length);
         }
        //Open the stream and read it back.
        using (StreamReader sr = fi.OpenText()) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                 Console.WriteLine(s);
             }
         }
     }
}

FileInfo.OpenText 方法:创建使用 UTF8 编码、从现有文本文件中进行读取的 StreamReader。
返回值:使用 UTF8 编码的新 StreamReader。 
FileInfo.CreateText 方法:创建写入新文本文件的 StreamWriter。 
返回值:新的StreamWriter。
下面说明 CreateText 方法和OpenText 方法。

using System;
using System.IO;
class Test 
{
    public static void Main() 
    {
        string path = @"c: test.txt";
        FileInfo fi = new FileInfo(path);
        if (!fi.Exists) 
        {
            //Create a file to write to.
            using (StreamWriter sw = fi.CreateText()) 
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }
        //Open the file to read from.
        using (StreamReader sr = fi.OpenText()) 
        {
            string s = "";
            while ((s = sr.ReadLine()) != null) 
            {
                Console.WriteLine(s);
            }
        }
    }
}