Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Get the bytes from a file

2009-02-05

The bytes of a file are the file’s data at the lowest level available, and in .NET bytes are usually stored in byte arrays. If you’re not trying to cheat in a role playing game by hacking some save file, why would you want to load the bytes of the file? You might want to pass the file something. Add it as an attachment in a mail or add it as a value in a database. In these cases, you are not bothered by the fact that the file is quite useless when stored in a byte array, in fact, you want the file as it is and you are not concerned by the issue that you can’t use the file’s format to access the actual data of the file.

Once the file is in a byte array, you can pass it to a SqlCommand object, convert it to a string, pass it to a web service, or indeed write it to disk.

To do this, create a FileInfo object to represent the file, and call the OpenRead method of the FileInfo object. OpenRead returns a FileStream object.

Dim Fi As New System.IO.FileInfo(“C:\Windows\notepad.exe”)
Dim S As System.IO.FileStream = Fi.OpenRead()

You can read the length of the file (in bytes) from the FileInfo object or the FileStream object. Either way, it is returned as a Long (64 bit integer), so it has to be converted to an Integer (32 bit). The largest amount of memory you can allocate is two gigabytes (Integer.MaxValue).  Also, in Visual Basic (unlike C#) you need to know the last index, not the size of, when you declare an array. Therefore, if you want an array with 3 elements, use Dim MyArray(2) As MyType.

Dim X(CType(S.Length – 1, Integer)) As Byte

Then, call the Read method of the FileStream. Pass in the buffer (in this case X), the offset and the number of bytes you want to read.

S.Read(X, 0, CType(S.Length, Integer))

Close and dispose the stream, and you are done!

S.Close()
S.Dispose()

Now, do what you want with the bytes of the file. You might want to remember the file ending of the original file. That can be good to know if you want to write the file back to disk.

Categories: Visual Basic 8

Tags: Disk IO, FileInfo, FileStream

Leave a Reply

Your email address will not be published. Required fields are marked *



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips