Dinindu Perera
Dinindu Perera

Reputation: 73

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();
            }

Upvotes: 3

Views: 2504

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

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

Upvotes: 3

adv12
adv12

Reputation: 8551

From the documentation on Stream.Read:

Return Value

Type: System.Int32

The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

So it appears that it's totally legal for Stream.Read to read less than the buffer length, provided it tells you that's what it did.

Upvotes: 0

C. Knight
C. Knight

Reputation: 749

Assuming that your file contains text then you could use a stream reader and just pass in your FileStream to the constructor (below I create a new FileStream to open a file):

using(StreamReader reader = new StreamReader(new FileStream("path", FileMode.Open)))
        {
            string data = reader.ReadToEnd();
        }

Upvotes: 1

Related Questions