Search This Blog

Sunday, February 22, 2009

Reading and Writing a File in VB 2005


တစ်ခါ တလေ Visual Basic 2005 ကိုသုံးပြီး ဖိုင်တွေရေးဖို့ ဖတ်ဖို့ လိုတတ်ပါတယ်။ အဲဒီ အခါ အလွယ်တကူ ကိုးကားလို့ရအောင် တစ်ချို့ ကုဒ်လေးတွေ ကို တင်လိုက်ပါတယ်။ အောက်က နမူနာ နှစ်ခုကတော့ ဒီနေရာက နေ ကိုးကားထားတာပါ။
Dim objStreamReader As StreamReader
Dim strLine As String

'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")

'Read the first line of text.
strLine = objStreamReader.ReadLine

'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
  'Write the line to the Console window.
  Console.WriteLine(strLine)

  'Read the next line.
  strLine = objStreamReader.ReadLine
Loop

'Close the file.
objStreamReader.Close()

Dim objStreamWriter As StreamWriter

'Pass the file path and the file name to the StreamWriter constructor.
objStreamWriter = New StreamWriter("C:\Testfile.txt")

'Write a line of text.
objStreamWriter.WriteLine("Hello World")
'Write a second line of text.
objStreamWriter.WriteLine("From the StreamWriter class")

'Close the file.
objStreamWriter.Close()


ဖိုင်ကိုသုံးနေတုန်း error တက်ခဲ့ရင် တော့ သုံးလက်စ ဖိုင်ကို မပိတ်နိုင်ပဲ ထွက်သွားတာမျိုး ဖြစ်နိုင်ပါတယ်။ အဲဒါကို တားဆီးဖို့ ကတော့ Try ... Finally ကိုအောက်ပါအတိုင်း သုံးနိုင်ပါတယ်။

Dim strLine As String
Dim sr As StreamReader = Nothing
Try
    sr = New StreamReader(fileName)
    strLine = sr.ReadToEnd()
Finally
    sr.Close()
End Try



Visual Basic 2005 မှာ Using ဆိုတဲ့ statement အသစ် က IDisposable object တွေကို အလိုအလျောက် release လုပ်ပေးနိုင်ပါတယ်။ Exception တစ်ခုခု ဖြစ်ရင် သူ့ရဲ့ caller ဆီကိုရောက်သွားမှာပါ။ အကယ်၍ အဲဒီ exception ကို ကိုယ့်ဟာကိုယ် catch လုပ်ချင်ရင်တော့ Try ... Catch ... Finally block ကိုပဲ သုံးရမှာပါ။

Dim strLine As String
Using sr As New StreamReader(fileName)
    strLine = sr.ReadToEnd
End Using


ဖိုင်ဖတ်တဲ့ အခါ ပိုပြီးလွယ်ကူ ရှင်းလင်း ချင်ရင် File.ReadAllText or File.ReadAllBytes static method ကိုသုံးလို့လဲ ရပါတယ်။
Log File

Log files တွေ အလွယ်တကူ ရေးဖို့ class တစ်ခု ကို ရေးကြည့် ထားပါတယ်။ သူ့ရဲ့ ကုဒ်တွေကို VB class for log file on GitHub ကနေ ယူလို့ သုံးလို့ ရပါတယ်။
'Author: Yan Naing Aye
'WebSite: http://cool-emerald.blogspot.sg/
'Updated: 2009 June 25
'-----------------------------------------------------------------------------
Imports System.IO
Public Class ClsLog
    Private mEnableLog As Boolean = False
    Private mLogFileDirectory As String = ""
    Private mLogFilePath As String = ""
    Private mLogFileLifeSpan As Integer = 0
    Private mLogFileFirstName As String = "AppName"
    Public Sub New()
        mEnableLog = False
        mLogFileDirectory = My.Application.Info.DirectoryPath
        mLogFileLifeSpan = 0
        mLogFileFirstName = My.Application.Info.AssemblyName
    End Sub
    Public Property LogFileLifeSpan() As Integer
        Get
            Return mLogFileLifeSpan
        End Get
        Set(ByVal value As Integer)
            mLogFileLifeSpan = IIf(value >= 0, value, 0)
        End Set
    End Property
    Public Property LogFileFirstName() As String
        Get
            Return mLogFileFirstName
        End Get
        Set(ByVal value As String)            
            mLogFileFirstName = value
        End Set
    End Property
    Public Property LogEnable() As Boolean
        Get
            Return mEnableLog
        End Get
        Set(ByVal value As Boolean)
            If value = True Then
                If Directory.Exists(Me.LogFileDirectory) Then
                    mEnableLog = value
                Else
                    mEnableLog = False
                    Throw New Exception("Invalid file directory.")
                End If
            Else
                mEnableLog = value
            End If
        End Set
    End Property
    Public Property LogFileDirectory() As String
        Get
            Return mLogFileDirectory
        End Get
        Set(ByVal value As String)
            value = Trim(value)
            If Directory.Exists(value) Then
                Dim i As Integer = value.Length - 1
                If (((value(i)) = "\") OrElse ((value(i)) = "/")) Then
                    value = value.Substring(0, i)
                End If
                mLogFileDirectory = value
            Else
                Throw New Exception("Invalid file directory.")
            End If
        End Set
    End Property
    Public ReadOnly Property LogFilePath() As String
        Get
            Return mLogFileDirectory & "\" & mLogFileFirstName & Format(Now, "-yyyy-MMM-dd") & ".log"
        End Get
    End Property
    Public Sub WriteLog(ByVal LogEntry As String)
        If mEnableLog = True Then
            mLogFilePath = mLogFileDirectory & "\" & mLogFileFirstName & Format(Now, "-yyyy-MMM-dd") & ".log"
            Dim objStreamWriter As StreamWriter = New StreamWriter(mLogFilePath, True)
            Try
                objStreamWriter.WriteLine(LogEntry)
            Catch ex As Exception
            Finally
                objStreamWriter.Close()
            End Try
        End If
    End Sub
    Public Sub WriteTimeAndLog(ByVal LogEntry As String)
        WriteLog(Now.ToLongTimeString & " " & LogEntry)
    End Sub
    Public Sub CleanupFiles()
        If mLogFileLifeSpan > 0 Then 'if life span is zero, there will be no cleaning up
            Try
                Dim LogFiles() As String = Directory.GetFiles(mLogFileDirectory)
                For Each LogFile As String In LogFiles
                    If (DateDiff("d", File.GetLastWriteTime(LogFile), Now) > mLogFileLifeSpan) _
                    AndAlso (Right(LogFile, 4) = ".log") Then
                        File.Delete(LogFile)
                    End If
                Next
            Catch ex As Exception
            End Try
        End If
    End Sub
End Class

No comments:

Post a Comment