StreamWriter 的应用

   StreamWriter 常用于向文本文件写字符串的, 默认的编码是 utf-8. 在 File.CreateText 方法说明中即有这样的例子:

      string path = @"c:\temp\MyTest.txt";
        if (!File.Exists(path))
        {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine("Hello");
                sw.WriteLine("And");
                sw.WriteLine("Welcome");
            }
        }

流指向开启的文本文件, 常用的方法就是 WriteLine, Write.

而在其构造函数中, 可以更改编码格式, 如下一种构造函数:

public StreamWriter(string path, bool append, Encoding encoding);
这样的一个示例:
StreamWriter sw = new StreamWriter(@"c:\test.txt", false, Encoding.Unicode);
sw.WriteLine("写入的一行文本.");
sw.Flush();
sw.Close();

posted @ 2011-05-28 19:09  沧海小小粟  阅读(322)  评论(0编辑  收藏  举报