如何:開啟並附加至記錄檔
StreamWriter 和 StreamReader 會在資料流中寫入字元和讀取字元。 下列程式碼範例會開啟用於輸入的 log.txt 檔案,或者,如果該檔案不存在,則會建立它,並將記錄資訊附加至檔案的結尾。 此範例接著會將檔案的內容寫入標準輸出以供顯示。
此範例的替代方法是,您可以將資訊儲存成單一字串或字串陣列,並使用 File.WriteAllText 或 File.WriteAllLines 方法來達成相同的功能。
注意
Visual Basic 使用者可以選擇使用 Log 類別或 FileSystem 類別所提供的方法和屬性來建立或寫入記錄檔。
範例
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.