DotNetFW Posted December 15, 2009 Posted December 15, 2009 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. :-\ Quote
Administrators PlausiblyDamp Posted December 16, 2009 Administrators Posted December 16, 2009 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. Quote Posting Guidelines FAQ Post Formatting Intellectuals solve problems; geniuses prevent them. -- Albert Einstein
DotNetFW Posted December 16, 2009 Author Posted December 16, 2009 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. Quote
Leaders snarfblam Posted December 16, 2009 Leaders Posted December 16, 2009 I'll kindly direct your attention over here. Quote [sIGPIC]e[/sIGPIC]
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.