共用方式為


HOW TO:開啟並附加至記錄檔

更新: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();
    }
}

請參閱

工作

HOW TO:建立目錄清單

HOW TO:讀取和寫入新建立的資料檔案

HOW TO:從檔案讀取文字

HOW TO:將文字寫入檔案

HOW TO:從字串中讀取字元

HOW TO:將字元寫入至字串

概念

基本檔案 I/O

參考

StreamWriter

StreamReader

File.AppendText

File.OpenText

StreamReader.ReadLine