Write file to stream in vb.net

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
Peter NordbergIT ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Kyle AbrahamsSenior .Net DeveloperCommented:
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

sarabandeCommented:
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 ManagerAuthor Commented:
Thanks for your contribution Sara.
CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Peter NordbergIT ManagerAuthor 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 DeveloperCommented:
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 DeveloperCommented:
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

sarabandeCommented:
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
Kyle AbrahamsSenior .Net DeveloperCommented:
sarabandeCommented:
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
käµfm³d 👽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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Peter NordbergIT ManagerAuthor Commented:
Hi and thanks for your contributions. The code received from käµfm³d worked perfectly.

Peter
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.