Reputation: 137
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
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
Reputation: 180798
Try this instead:
while (inputstream.Position <= inputstream.Length)
{
writestream.WriteByte((byte)inputstream.ReadByte());
}
Upvotes: 2
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
Reputation: 50225
You're only writing every other byte because you're consuming one in the while
check.
Upvotes: 9