Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

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:

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. :-\

  • Administrators
Posted

You don't need to create a variable to use the File object so you could remove a couple of lines

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.

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Posted

Hi,

Thanks buddy :)

One guy told me I could use it all in a single line:

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.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...