Connecting Tech Pros Worldwide Forums | Help | Site Map

How to read a stream and save it as byte array

Newbie
 
Join Date: Dec 2008
Posts: 12
#1: Jun 25 '09
Hello everyone,

I try to read a stream and save it as byte array to add it later to zip file.
this is the code that I use
Expand|Select|Wrap|Line Numbers
  1. Dim totalbytes As Byte() = Nothing
  2. Dim iBytesRead As Integer
  3. Dim sChunks As FileStream = File.OpenRead("c:\myfile.wav")
  4. Dim Totalread As Int64 = 0
  5. ReDim totalbytes(sChunks.Length)
  6. Do
  7. iBytesRead = sChunks.Read(totalbytes, Totalread, Totalread+ 1048576)
  8. Totalread+= iBytesRead
  9. Loop While Not iBytesRead = 0
  10. sChunks.Close()
  11. Return totalbytes
  12.  
but there is something is not correct,
Can you please help me in that.

Thank you

insertAlias's Avatar
Forum Leader
 
Join Date: Apr 2008
Location: San Antonio, TX (USA)
Posts: 2,608
#2: Jun 25 '09

re: How to read a stream and save it as byte array


Here's how I do my reading in C# :
Expand|Select|Wrap|Line Numbers
  1. FileStream fs = File.OpenRead(filePath);
  2. byte[] buffer = new byte[fs.Length];
  3. fs.Read(buffer, 0, (int)fs.Length);
  4. fs.Flush();
  5. fs.Close();

So I would suggest cutting out your lines 6 through 9 and replacing them with something like this:
Expand|Select|Wrap|Line Numbers
  1. sChunks.Read(totalbytes, 0, totalbytes.Length)
You might have to cast totalbytes.Length from an Int 64 to an Int 32, but I forget how to cast in VB.NET.

Hope that helps.

[EDIT]
For future reference, "there is something is not correct" is not a good enough explanation. You need to tell us what it is doing wrong, and what, if any, exceptions you are getting. Please be more descriptive in the future.
Newbie
 
Join Date: Dec 2008
Posts: 12
#3: Jun 25 '09

re: How to read a stream and save it as byte array


Thank you for reply

Actually I can read all bytes by File.ReadAllBytes but I need to read this file with progress.
If I read it byte by byte it will take a long time (it is take more than 5 min to read 30MB).
So I think about this way, but there is something wrong, I dont know what is it.

Finally, I am sorry about my English.

Thanks
Newbie
 
Join Date: Dec 2008
Posts: 12
#4: Jun 25 '09

re: How to read a stream and save it as byte array


Also I found this sample on internet, but because I dont know c# then I dont understand it.
Attached Files
File Type: zip AsyncStream.zip (37.0 KB, 6 views)
Reply