Gerry
Gerry

Reputation: 137

Read write using Stream.Readbyte and stream.Writebyte in C#

What is wrong with the following code?

        Stream inputstream = File.Open("e:\\read.txt", FileMode.Open);
        Stream writestream = File.Open("e:\\write.txt", FileMode.OpenOrCreate);

        do
        {
            writestream.WriteByte((byte)inputstream.ReadByte());
        }
        while (inputstream.ReadByte() != -1);

read.txt has "the quick brown fox jumped over the lazy dog."

Whereas the write.txt file contains few contents skimmed "teqikbonfxjme vrtelz o."

Upvotes: 0

Views: 9024

Answers (4)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

You are writing only odd bytes, because you are skipping even bytes when do another reading in where condition.

Modify your code this way:

int byteRead;
while((byteRead = inputstream.ReadByte()) != -1)
   writestream.WriteByte((byte)byteRead);

BTW you can use File.Copy("e:\\read.txt", "e:\\write.txt") instead.

Upvotes: 5

Robert Harvey
Robert Harvey

Reputation: 180798

Try this instead:

while (inputstream.Position <= inputstream.Length)
{
    writestream.WriteByte((byte)inputstream.ReadByte());
}

Upvotes: 2

nrofis
nrofis

Reputation: 9766

The inputstream.ReadByte() method makes you cursor to move by one.

You need to read the byte once, and if it not -1 then write it. Just like that:

int read = inputstream.ReadByte();
while (read != -1)
{ 
    writestream.WriteByte((byte)read ); 
    read = inputstream.ReadByte();
} 

Upvotes: 1

Austin Salonen
Austin Salonen

Reputation: 50225

You're only writing every other byte because you're consuming one in the while check.

Upvotes: 9

Related Questions