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

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值