Saturday, July 12, 2008

Reading and Writing to Streams

In the following example, I used FileStream to explain how reading and writing to steams work.

The example is self explanatory. It reads the data from TestRead.dat and writes it to TestWrite.dat.

ReadCount is 0 when Read has reached the end of the file; otherwise it is 1<=ReadCount<=100. ReadCount can change every time that Read method is called in the loop.

Buffer length can be modified but please note that it has to be able to accommodate the number of bytes returned by Read method.

 

using (FileStream ReadStream = new FileStream("c:\\TestRead.dat", FileMode.Open))
            {
                using (FileStream WriteStream = new FileStream("c:\\TestWrite.dat", FileMode.Create))
                {
                    byte[] Buffer = new byte[101];

                    int ReadCount = 0;
                    do
                    {
                        ReadCount = ReadStream.Read(Buffer, 0, 100);
                        WriteStream.Write(Buffer, 0, ReadCount);

                    } while (ReadCount != 0);
                }
            }

No comments: