Dinindu Perera Dinindu Perera - 5 months ago 35
C# Question

FileStream.Read - Read a stream without using a loop

How would I read a filestream without using a loop? When I use this code it only reads 5714 bytes instead of 1048576 bytes

byte[] Buffer = new byte[1048576];
ByteSize = downloadstream.Read(Buffer, 0,Buffer.Lenght);

If I use this loop it works fine

while ((ByteSize = downloadstream.Read(Buffer, 0, Buffer.Length)) > 0)
//write stream to file

So how would I read an entire stream without using a loop?
Thanks, would appreciate any help.

UPDATE: I have to read all of the data into a buffer and then write it. Sorry I didn't mention this earlier.


If you want to read the entire file in one go, I suggest using File.ReadAllBytes for binary files:

 byte[] data = File.ReadAllBytes(@"C:\MyFile.dat");

And File.ReadAllText / File.ReadAllLines for text ones:

 string text = File.ReadAllText(@"C:\MyFile.txt");

 string[] lines = File.ReadAllText(@"C:\MyOtherFile.txt");

Edit: in case of web

  byte[] data;

  using (WebClient wc = new WebClient()) {
    wc.UseDefaultCredentials = true; // if you have a proxy etc.

    data = wc.DownloadData(myUrl); 

when myUrl is @"https://www.google.com" I've got data.Length == 45846