Jason Shoulders
Jason Shoulders

Reputation: 659

Read Binary File Python to Vb.net

I have two simple lines of Python Script where the len(fileData) is 3530

Python

   imgFile = file(inputFile, "rb")
   fileData = imgFile.read()

and I'm trying to convert it to vb.net. If I do this, I can get the length to match up but I'm stuck trying to actually get the data itself to a string variable:

VB.NET

    Using reader As New BinaryReader(File.Open(inputFile, FileMode.Open))
    Dim length As Integer = reader.BaseStream.Length
    End Using

I tried using

VB.NET

    Dim fileData As String = File.ReadAllText(inputFile)

But when I do len(fileData), it 3528, so something is amiss.

I just want to open and read the binary file to a string variable and see the length of it is 3530 as it is currently, correctly working in the Python script.

What am I missing?

Upvotes: 0

Views: 250

Answers (1)

dummy
dummy

Reputation: 4284

You are missing the fact that not every binary data can be represented as String.

If you just want the raw data and it's length you can read the file into a byte array:

    Dim myBytes() As Byte = IO.File.ReadAllBytes("myFile.dat")
    Console.WriteLine(myBytes.Length)

If really need the data as a String, you have to think about the encoding of the String:

    Dim myString As String = IO.File.ReadAllText("myFile.dat", System.Text.Encoding.UTF8)        

ReadAllText() without the second parameter assumes an encoding (most likely) Encoding.Default which is ANSI with you system codepage.

Upvotes: 1

Related Questions