基本文件的I/O --打开并追加到日志文件

来源:互联网 发布:世界网络银行商城手机 编辑:程序博客网 时间:2024/06/11 06:52

StreamWriter  StreamReader 向流写入字符并从流读取字符。下面的代码示例打开 log.txt 文件(如果文件不存在则创建文件)以进行输入,并将信息附加到文件尾。然后将文件的内容写入标准输出以便显示。除此示例演示的做法外,还可以将信息存储为单个字符串或字符串数组,WriteAllText 或 WriteAllLines方法可以用于实现相同的功能。

        public static void Main(string[] args)
        {
            using (StreamWriter w = File.AppendText("log.txt"))//Create the "log.txt" file(默认路径Debug文件夹)。
            {
                Log("Test1", w);
                Log("Test2", w);
                w.Close();// Close the writer and underlying file.
            }
            using (StreamReader r = File.OpenText("log.txt"))// Open and read the file.
            {
                DumpLog(r);
            }
            Console.ReadKey();
        }
        public static void Log(String logMessage, TextWriter w)
        {
            w.Write("\r\nLog Entry : ");
            w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
                DateTime.Now.ToLongDateString());
            w.WriteLine("  :");
            w.WriteLine("  :{0}", logMessage);
            w.WriteLine("-------------------------------");
            // Update the underlying file.
            w.Flush();
        }
        public static void DumpLog(StreamReader r)
        {
            // While not at the end of the file, read and write lines.
            String line;
            while ((line = r.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
            r.Close();
        }

        

 参阅MSDN文档:

  (1)向文件中写入文本

  (2)从文件中读取文本

0 0
原创粉丝点击