HOW TO:開啟並附加至記錄檔
更新:2007 年 11 月
StreamWriter 和 StreamReader 會撰寫字元至資料流,以及讀取資料流中的字元。下列程式碼範例開啟輸入的 log.txt 檔案,或建立檔案 (如果它不存在),並附加資訊至檔案結尾。接著寫入檔案內容至標準輸出以供顯示。這個範例有一個替代方法:可以將這項資訊儲存為單一字串或字串陣列,而且 WriteAllText 或 WriteAllLines 方法可用來達成相同的功能。
![]() |
---|
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();
}
}