Avatar of Peter Nordberg
Peter NordbergFlag for Sweden asked on

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
Visual Basic.NETVB Script.NET ProgrammingC#

Avatar of undefined
Last Comment
Peter Nordberg

8/22/2022 - Mon
Kyle Abrahams

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

sarabande

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
ASKER
Peter Nordberg

Thanks for your contribution Sara.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER
Peter Nordberg

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 Abrahams

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 Abrahams

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

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
sarabande

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 Abrahams

sarabande

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
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
kaufmed

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
Peter Nordberg

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

Peter