如何:打开并追加到日志文件How to: Open and append to a log file

StreamWriterStreamReader 对流执行字符写入和读取操作。StreamWriter and StreamReader write characters to and read characters from streams. 下面的代码示例打开 log.txt 文件以供输入,或创建该文件(如果尚无文件的话),并将日志信息追加到文件末尾 。The following code example opens the log.txt file for input, or creates it if it doesn't exist, and appends log information to the end of the file. 然后,示例将文件内容写入标准输出以供显示。The example then writes the contents of the file to standard output for display.

作为此示例的替换方法,可以将信息存储为一个字符串或字符串数组,并使用 File.WriteAllTextFile.WriteAllLines 方法实现相同的功能。As an alternative to this example, you could store the information as a single string or string array, and use the File.WriteAllText or File.WriteAllLines method to achieve the same functionality.

备注

Visual Basic 用户可以选择使用 Log 类或 FileSystem 类提供的方法和属性,以创建或写入日志文件。Visual Basic users may choose to use the methods and properties provided by the Log class or FileSystem class for creating or writing to log files.

示例Example

using System;
using System.IO;

class DirAppend
{
    public static void Main()
    {
        using (StreamWriter w = File.AppendText("log.txt"))
        {
            Log("Test1", w);
            Log("Test2", w);
        }
        
        using (StreamReader r = File.OpenText("log.txt"))
        {
            DumpLog(r);
        }
    }

    public static void Log(string logMessage, TextWriter w)
    {
        w.Write("\r\nLog Entry : ");
        w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}");
        w.WriteLine("  :");
        w.WriteLine($"  :{logMessage}");
        w.WriteLine ("-------------------------------");
    }

    public static void DumpLog(StreamReader r)
    {
        string line;
        while ((line = r.ReadLine()) != null)
        {
            Console.WriteLine(line);
        }
    }
}
// The example creates a file named "log.txt" and writes the following lines to it,
// or appends them to the existing "log.txt" file:

// Log Entry : <current long time string> <current long date string>
//  :
//  :Test1
// -------------------------------

// Log Entry : <current long time string> <current long date string>
//  :
//  :Test2
// -------------------------------

// It then writes the contents of "log.txt" to the console.
Imports System.IO

Class DirAppend
    Public Shared Sub Main()
        Using w As StreamWriter = File.AppendText("log.txt")
            Log("Test1", w)
            Log("Test2", w)
        End Using

        Using r As StreamReader = File.OpenText("log.txt")
            DumpLog(r)
        End Using
    End Sub

    Public Shared Sub Log(logMessage As String, w As TextWriter)
        w.Write(vbCrLf + "Log Entry : ")
        w.WriteLine($"{DateTime.Now.ToLongTimeString()} {DateTime.Now.ToLongDateString()}")
        w.WriteLine("  :")
        w.WriteLine($"  :{logMessage}")
        w.WriteLine ("-------------------------------")
    End Sub

    Public Shared Sub DumpLog(r As StreamReader)
        Dim line As String
        line = r.ReadLine()
        While Not (line Is Nothing)
            Console.WriteLine(line)
            line = r.ReadLine()
        End While
    End Sub
End Class

' The example creates a file named "log.txt" and writes the following lines to it,
' or appends them to the existing "log.txt" file:

' Log Entry : <current long time string> <current long date string>
'  :
'  :Test1
' -------------------------------

' Log Entry : <current long time string> <current long date string>
'  :
'  :Test2
' -------------------------------

' It then writes the contents of "log.txt" to the console.

请参阅See also