0

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?

1
  • Whenever my binary data is missing a few bytes, I always suspect that the file wasn't opened in binary mode, so all "\r\n" character sequences get "helpfully" turned into just "\n". Not sure how you would fix this in VB, it's just something I have encountered in many languages. Commented Oct 9, 2014 at 16:35

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

If I do that last line with System.Text.Encoding.ASCII, it comes back with the length I was expecting it to be. Using UTF8, it's still 2 characters shy.
UTF8 was just an purposefully bad example. You really shouldn’t read binary data into Strings. On the other hand it really depends, what on want to archive.
Thanks for the feedback. I'm working on a larger project converting some Python script to Vb.Net so I may end up changing how I use it, but I wanted to keep everything intact with how it appears to be at the moment. The next step appears to take that binary information and POST it to an http connection. I felt like if the length didn't match that I'd have no shot getting it to work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.