○VB.net ファイル読み書き

■ログをファイルに追記する

Public Class FileLog
    Private sw As System.IO.StreamWriter
    Sub New(ByVal filename As String)
        sw = New System.IO.StreamWriter(filename, True, System.Text.Encoding.GetEncoding(932))
    End Sub

    Public Function addLog(ByVal str As String)
        sw.WriteLine(Now.ToString() + "  :  " + str)
        sw.Flush()
    End Function

    Protected Overrides Sub Finalize()
        sw.Close()
        MyBase.Finalize()
    End Sub
End Class

■ファイルから一行づつ呼び出す

Private fileread As New FileRead("log.txt")
Dim str As String
While (fileread.read(str))
   Debug.WriteLine(str)
End While

Public Class FileRead
    Private sr As System.IO.StreamReader
    Sub New(ByVal filename As String)
        sr = New System.IO.StreamReader(filename, System.Text.Encoding.GetEncoding(932))
    End Sub

    Public Function read(ByRef str As String) As Boolean
        str = sr.ReadLine()
        Return (sr.Peek() >= 0)
    End Function

    Protected Overrides Sub Finalize()
        sr.Close()
        MyBase.Finalize()
    End Sub
End Class




▲トップページ > Visual BASIC と C#