如何:打开并追加到日志文件

更新:2007 年 11 月

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

说明:

Visual Basic 用户可以选择使用由 My.Application.Log 或 My.Computer.FileSystem 对象提供的方法和属性创建或写入日志文件。有关更多信息,请参见 My.Application.Log 对象My.Computer.FileSystem 对象

示例

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
    Public Shared Sub Main()
        Using w As StreamWriter = File.AppendText("log.txt")
            Log("Test1", w)
            Log("Test2", w)
            ' Close the writer and underlying file.
            w.Close()
        End Using
        ' Open and read the file.
        Using r As StreamReader = File.OpenText("log.txt")
            DumpLog(r)
        End Using
    End Sub
    Public Shared Sub Log(ByVal logMessage As String, ByVal w As TextWriter)
        w.Write(ControlChars.CrLf & "Log 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()
    End Sub
    Public Shared Sub DumpLog(ByVal r As StreamReader)
        ' While not at the end of the file, read and write lines.
        Dim line As String
        line = r.ReadLine()
        While Not line Is Nothing
            Console.WriteLine(line)
            line = r.ReadLine()
        End While
        r.Close()
    End Sub
End Class
using System;
using System.IO;
class DirAppend
{
    public static void Main(String[] args)
    {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            Log ("Test1", w);
            Log ("Test2", w);
            // Close the writer and underlying file.
            w.Close();
        }
        // Open and read the file.
        using (StreamReader r = File.OpenText("log.txt"))
        {
            DumpLog (r);
        }
    }
    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();
    }
}

请参见

任务

如何:创建目录列表

如何:对新建的数据文件进行读取和写入

如何:从文件读取文本

如何:向文件写入文本

如何:从字符串中读取字符

如何:向字符串写入字符

概念

基本的文件 I/O

参考

StreamWriter

StreamReader

File.AppendText

File.OpenText

StreamReader.ReadLine