Write file to stream in vb.net

Peter Nordberg
Peter Nordberg used Ask the Experts™
on
Hi,

I have this c# sub that I want to convert to vb. The main idea is to take the file contained in the filename and write it to the stream in chunks. It works fine in C# but I can't get it to work in vb.net. This is the version in c#:
 public void WriteFile(Stream stream, string filename)
        {
            using (FileStream readIn = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                readIn.Seek(0, SeekOrigin.Begin); // move to the start of the file
                byte[] fileData = new byte[BufferSize];
                int bytes;
                while ((bytes = readIn.Read(fileData, 0, BufferSize)) > 0)
                {
                    // read the file data and send a chunk at a time
                    stream.Write(fileData, 0, bytes);
                }
            }
        }

Open in new window

And this is two versions I've tried in vb without success. In the first the code jumps over the while loop and doesn't write to the stream and in the second it complains that I can't close before all the bytes are read.

 Public Sub WriteFile(ByRef stream As Stream, ByVal filename As String)
            Using readIn As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
                readIn.Seek(0, SeekOrigin.Begin)
                Dim fileData As Byte() = New Byte(BufferSize - 1) {}

                Using rdr As New BinaryReader(readIn)
                    'Read BufferSize bytes from the file
                    Dim bytes(BufferSize) As Byte
                    'Dim bytesRead As Integer = rdr.Read(bytes, 0, BufferSize)
                    Dim bytesRead As Integer = 0

                    While ((bytesRead = rdr.Read(bytes, 0, BufferSize)) > 0)
                        stream.Write(bytes, 0, bytesRead)
                    End While
                End Using
            End Using
        End Sub

Open in new window


 Public Sub WriteFile(ByRef stream As Stream, ByVal filename As String)
            Using readIn As New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
                readIn.Seek(0, SeekOrigin.Begin)
                Using rdr As New BinaryReader(readIn)

                    Using wtr As New BinaryWriter(stream)
                        ' read all bytes
                        Dim bytes() As Byte = rdr.ReadBytes(readIn.Length)
                        ' write all bytes
                        wtr.Write(bytes)

                    End Using

                    rdr.Close()
                End Using

            End Using
        End Sub

Open in new window


If someone can help me get it right I would be grateful.

Peter
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Kyle AbrahamsSenior .Net Developer

Commented:
Did you try a code converter?
http://converter.telerik.com/
 Public Sub WriteFile(ByVal stream As Stream, ByVal filename As String)
        Using readIn As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
            readIn.Seek(0, SeekOrigin.Begin)
            Dim fileData As Byte() = New Byte(BufferSize - 1) {}
            Dim bytes As Integer

            While (CSharpImpl.__Assign(bytes, readIn.Read(fileData, 0, BufferSize))) > 0
                stream.Write(fileData, 0, bytes)
            End While
        End Using
    End Sub

    Private Class CSharpImpl
        <Obsolete("Please refactor calling code to use normal Visual Basic assignment")>
        Shared Function __Assign(Of T)(ByRef target As T, value As T) As T
            target = value
            Return value
        End Function
    End Class
End Class

Open in new window

Top Expert 2016

Commented:
Kyle, the question here is a follow-up from #a42744272

the VB code he used was created by a converter (and similar to the code you posted), but the result written to the stream was different to that made by the original C# function. one reason probably was that the stream was passed by value in VB. but also the CSharpImpl.__Assign looks weird and the converter itself made a comment that it was obsolete.

the question here is for valid vb code which reads all bytes of a pdf file and write the bytes to a System.IO.Stream that already contains string data. furthermore, after writing the pdf data, the calling sub writes again to the stream. the length of all data written must be the same as in the c# program. otherwise there was an error.

Sara
Peter NordbergIT Manager

Author

Commented:
Thanks for your contribution Sara.
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Peter NordbergIT Manager

Author

Commented:
Hi Kyle,

This was the very first thing I did. I used Teleriks converter and got exactly the result you are showing, but it doesn't work, and the code I pasted here are later alterations - but none of them works.
Kyle AbrahamsSenior .Net Developer

Commented:
Hi Peter,

Is the PDF opened by chance or can you make a copy of a pdf or try a different PDF?  Just trying to isolate why it wouldn't read.

The issue seems to be on the reading side of things and can you confirm you have a buffersize declared in your VB app?
Kyle AbrahamsSenior .Net Developer

Commented:
Also from:
https://docs.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/drives-directories-files/how-to-read-from-binary-files

it looks like they don't assign the integer.  That might be your error.

lastly have you tried

rdr.CopyTo(stream)

Open in new window

Top Expert 2016

Commented:
rdr.CopyTo(stream)

MS docs don't have a reference for  StreamReader.CopyTo in VB.NET


the issue seems to be on the reading side of things

you can check that by calculating the total of bytes (sum-up variable bytesRead) returned from rdr.

if the total is the same as in the c# function, it is not the reading side which is wrong.

we then could read and write byte for byte what is slow but might solve the issues in WriteFile.

Sara
Top Expert 2016

Commented:
thanks.

it is that i didn't find any vb code sample with copyTo. and that the file must not be big because copyTo would allocate only one buffer for the data.

Sara
Glanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015
Commented:
VB as a language functions a bit differently than C#. I suppose that the inline assignment may be giving your grief. Have you tried extracting the assignment out:

Public Sub WriteFile(ByRef stream As Stream, ByVal filename As String)
    Using readIn As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        readIn.Seek(0, SeekOrigin.Begin)
        Dim fileData As Byte() = New Byte(BufferSize - 1) {}

        Using rdr As New BinaryReader(readIn)
            'Read BufferSize bytes from the file
            Dim bytes(BufferSize) As Byte
            'Dim bytesRead As Integer = rdr.Read(bytes, 0, BufferSize)
            Dim bytesRead As Integer = 0

            Do
                bytesRead = rdr.Read(bytes, 0, BufferSize)

                If bytesRead > 0 Then
                    stream.Write(bytes, 0, bytesRead)
                End If
            Loop While (bytesRead > 0)
        End Using
    End Using
End Sub

Open in new window

Peter NordbergIT Manager

Author

Commented:
Hi and thanks for your contributions. The code received from käµfm³d worked perfectly.

Peter

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial