Search code examples
c#filestream

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. I have to read all of the data into a buffer and then write it. Sorry I didn't mention this earlier.

EDIT: You can use this code as well to read a stream into a buffer at once:

using (var streamreader = new MemoryStream())
            {
                stream.CopyTo(streamreader);
                buffer = streamreader.ToArray();
            }

Solution

  • 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