ログ ファイルのオープンと追加

StreamWriter はストリームに文字を書き込み、StreamReader はストリームから文字を読み取ります。入力用として log.txt ファイルを開くか、ファイルが存在しない場合は作成し、ファイルの末尾に情報を追加するコードの例を次に示します。その後で、ファイルの内容を表示するために標準出力に書き込みます。

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
    Public Shared Sub Main()
        Dim w As StreamWriter = File.AppendText("log.txt")
        Log("Test1", w)
        Log("Test2", w)
        ' Close the writer and underlying file.
        w.Close()
        ' Open and read the file.
        Dim r As StreamReader = File.OpenText("log.txt")
        DumpLog(r)
    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

[C#]
using System;
using System.IO;
class DirAppend
{
    public static void Main(String[] args)
    {
        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.
        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 クラス | AppendText メソッド | OpenText メソッド | ReadLine メソッド