2012-10-18 47 views
0

以下代碼有什麼問題?使用C#中的Stream.Readbyte和stream.Writebyte進行讀取寫入#

 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有「快速的棕色狐狸跳過懶惰的狗」。

而write.txt文件包含的內容很少,被刪除了「teqikbonfxjme vrtelz o」。

回答

8

由於您在while檢查中佔用一個字節,所以您只寫了其他每個字節。

+0

謝謝。哎呀,我必須提高自己的常識 – Gerry

+0

只需使用調試器進行一些練習,您就可以立即「搖擺」。 –

2

試試這個:

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

你只寫奇字節,因爲你是在where情況另做閱讀時跳過偶數字節。

修改你的代碼是這樣的:

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

順便說一句,你可以使用File.Copy("e:\\read.txt", "e:\\write.txt")代替。

0

inputstream.ReadByte()方法讓你的光標移動一個。

您需要讀取一次該字節,如果不是-1則寫入。就像那樣:

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