System.Convert.FromBase64String

G

Guest

I have an application that gets a shipping label from DHL. The shipping
label is sent to me via XML. I am able to display the text in a text box. I
need to convert it to a gif file. The field is defined as
<image imageformat="gif" dt:dt="bin.base64"
xmlns:dt="urn:schemas-microsoft-com:datatypes">

I tried the function below but the file it generates I could not view in IE.
Anyone have any ideas?

Public Sub ConvertFiletoBinary()
Dim inFile As System.IO.StreamReader
Dim base64String As String
Dim inputFilename As String = "c:\j.txt"
Dim outputfilename As String = "C:\nike.gif"
Try
Dim base64CharArray() As Char
inFile = New System.IO.StreamReader(inputFileName, _
System.Text.Encoding.ASCII)
base64CharArray = New Char(inFile.BaseStream.Length) {}
inFile.Read(base64CharArray, 0, inFile.BaseStream.Length)
base64String = New String(base64CharArray, _
0, _
base64CharArray.Length - 1)
Catch exp As System.Exception
' Error creating stream or reading from it.
System.Console.WriteLine("{0}", exp.Message)
Return
End Try

' Convert the Base64 UUEncoded input into binary output.
Dim binaryData() As Byte
Try
binaryData = System.Convert.FromBase64String(base64String)
Catch exp As System.ArgumentNullException
System.Console.WriteLine("Base 64 string is null.")
Return
Catch exp As System.FormatException
System.Console.WriteLine("Base 64 length is not 4 or is " + _
"not an even multiple of 4.")
Return
End Try

'Write out the decoded data.
Dim outFile As System.IO.FileStream
Try
outFile = New System.IO.FileStream(outputFileName, _
System.IO.FileMode.Create, _
System.IO.FileAccess.Write)
outFile.Write(binaryData, 0, binaryData.Length - 1)
outFile.Close()
Catch exp As System.Exception
' Error creating stream or writing to it.
System.Console.WriteLine("{0}", exp.Message)
End Try

End Sub
 
M

Mattias Sjögren

Dim base64CharArray() As Char
inFile = New System.IO.StreamReader(inputFileName, _
System.Text.Encoding.ASCII)
base64CharArray = New Char(inFile.BaseStream.Length) {}
inFile.Read(base64CharArray, 0, inFile.BaseStream.Length)
base64String = New String(base64CharArray, _
0, _
base64CharArray.Length - 1)

The base64CharArray you allocate is one element too large, I don't
know if that could cause any errors later on.

It would be easier to just replace the last three lines with

base64String = inFile.ReadToEnd()


Mattias
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top