Sunday, February 22, 2009

Reading and Writing a File in VB 2005

We occasionally need to read or write a file in Visual Basic 2005. For an easy reference, we want to post a few code here. The following two examples of reading and writing a file are from this web site.

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()


If an error occurs while processing the file, the current method might be exited before you have an opportunity to close the file. A Try ... Finally block can be used to avoid this problem.

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 has a new Using statement that can automatically release one or more IDisposable objects. Any exception will be reported to callers. If you want to catch exceptions, you need a complete Try ... Catch ... Finally block.

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


Reading a text file can also be performed more easily by means of the new File.ReadAllText static method. For binary file, File.ReadAllBytes can be used.
Log File

We have written a class to write log files easily. Its source code can be seen and downloaded 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

Sunday, February 1, 2009

FAT32 Format

I want to use my removable hard disk on both Windows and Linux machines. The problem was that Linux does not support NTFS and I could not format my disk to FAT32 in Windows XP. Using "format x: /fs:fat32" command ended in vain because it was larger than 32 GB. I also tried to format in Windows Vista but it still did not work in Linux. Later, I found a small and easy to use freeware program called fat32format.exe that can format large hard disks very fast. Just partition the drive, then type "fat32format X:" where X is the partition letter. Formatting a drive in FAT32 will allow it to be read by other operating systems, such as Mac, Linux, older versions of Windows, etc.