Link to home
Start Free TrialLog in
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
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

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

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
Avatar of Peter Nordberg

ASKER

Thanks for your contribution Sara.
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.
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?
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

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
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
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi and thanks for your contributions. The code received from käµfm³d worked perfectly.

Peter