When reading file content I tend to use the following:
- Dim contents As New StringBuilder()
-
Dim enc As Encoding = New UTF8Encoding()
-
-
Using fStream As FileStream = New FileStream("servercache.dat", FileMode.Open, FileAccess.Read)
-
-
' The maximum bytes to read.
-
Dim toRead As Int32 = 1024 ' 1Kb
-
-
' The buffer for read bytes.
-
Dim buffer(toRead - 1) As Byte
-
-
' The number of bytes that have been read.
-
Dim read As Int32 = fStream.Read(buffer, 0, toRead)
-
-
' While there is any data that has been read
-
Do While read > 0
-
-
' Get the string from the byte array.
-
contents.Append(enc.GetString(buffer, 0, read))
-
-
' Read next batch of data into the buffer.
-
read = fStream.Read(buffer, 0, toRead)
-
Loop
-
-
fStream.Close()
-
End Using
This code assumes an import of the System.Text namespace. The encoding used will be dependant upon the encoding of the file. The instantiation of the enc object could also have been written as:
- Dim enc As Encoding = Encoding.UTF8
A couple of items of note are the Using block and the StringBuilder.
The Using block causes the Dispose method of an iDisposable object to be called once that item is out of scope.
The StringBuilder is used instead of a string due to the iterative process of copying the contents of the file. A string is immutable so every time a concatanation is made a new instance of the object is created and the existing instance recreated. A StringBuilder is mutable and so should give better performance, particularly with larger files. To retrieve the string use the ToString() method of the StringBuilder.