We help IT Professionals succeed at work.

Write file to stream in vb.net

339 Views
Last Modified: 2018-11-29
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

Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT

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

CERTIFIED EXPERT
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.
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
CERTIFIED EXPERT

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
CERTIFIED EXPERT

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

CERTIFIED EXPERT
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
Kyle AbrahamsSenior .Net Developer
CERTIFIED EXPERT

Commented:
CERTIFIED EXPERT
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
CERTIFIED EXPERT
Most Valuable Expert 2011
Top Expert 2015
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Peter NordbergIT Manager

Author

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

Peter
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.