Read a file

DotNetFW

Newcomer
Joined
Dec 15, 2009
Messages
2
Hello forum :)
I am happy I'm here, and there are lot of programmers who love .NET. :p
Well, this is my code to read a file:
Visual Basic:
Dim f As System.IO.File 'Reference to file object
Dim fs As System.IO.FileStream  'Reference to Filestream object
fs = f.Open(Filename.Text, IO.FileMode.Open, IO.FileAccess.Read)
' Allocate a byte array accoording to file length
Dim b(fs.Length - 1) As Byte
' Read the entire file
fs.Read(b, 0, fs.Length)
' Cleanup file+Stream
f = Nothing
fs.Close()
Do you guys think this is a correct way to do this?
Is there a better and easier way to do the same in VB.NET?
While I am reading some tutorials on .NET language and file operations but I needed a quicker way to know this. :-\
 
You don't need to create a variable to use the File object so you could remove a couple of lines
Visual Basic:
Dim fs As System.IO.FileStream  'Reference to Filestream object
fs = System.IO.File.Open(Filename.Text, IO.FileMode.Open, IO.FileAccess.Read)
' Allocate a byte array accoording to file length
Dim b(fs.Length - 1) As Byte
' Read the entire file
fs.Read(b, 0, fs.Length)
' Cleanup file+Stream
fs.Close()
The code will work fine, howver if the size of the file is very large then allocating the byte array could consume a lot of memory in one go, depending on what you are doing with the file you might be able to read it a chunk at a time to reduce memory overheads.

If the file is text based then you might find using a StringReader makes reading from the file a lot easier.
 
Hi,
Thanks buddy :)
One guy told me I could use it all in a single line:
Visual Basic:
Dim bytes() As Byte = File.ReadAllBytes("Filename.txt")
Yes?
I just have one more question that in this case we must pass the path to an existing file to the ReadAllBytes method.
What if we have our file contents already in a TextBox?
How can I read all bytes in a TextBox?
Thank you.
 
Back
Top