现在的位置: 首页 > 综合 > 正文

StreamWriter 的应用

2012年10月21日 ⁄ 综合 ⁄ 共 620字 ⁄ 字号 评论关闭

   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();

抱歉!评论已关闭.