我有一個旨在完成一個簡單的任務以下WriteFileToStream功能:從文件中獲取數據,並將其複製到流。
我原來使用Stream.CopyTo(Stream)方法。但是,經過長時間的調試過程後,我發現這是導致我的處理管道中出現「損壞的數據」錯誤的原因。
梗概:
使用Stream.CopyTo(流)方法產生65536個字節的數據和該流不正確地處理。
使用Stream.Write(...)方法會正確生成45450字節的數據和流處理。
問題:
有人能看到爲什麼CopyTo用於以下用途都有可能造成多餘的數據被寫入到流?
請注意:WriteFileToStream最終代碼的答案被帶到了這樣一個問題:Save and load MemoryStream to/from a file
public static void WriteFileToStream(string fileName, Stream outputStream)
{
FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
long fileLength = file.Length;
byte[] bytes = new byte[fileLength];
file.Read(bytes, 0, (int)fileLength);
outputStream.Write(bytes, 0, (int)fileLength);
file.Close();
outputStream.Close();
// This was corrupting the data - adding superflous bytes to the result...somehow.
//using (FileStream file = File.OpenRead(fileName))
//{
// //
// file.CopyTo(outputStream);
//}
}
從看着你混合起來的代碼 - *你*的代碼是越野車,並在上面寫上多餘的數據到'目的地,而'CopyTo()'實際上工作正常。 – Lucero 2012-08-03 16:55:57
致智者:作爲開發者,這總是我們的錯。它(幾乎)從來不是操作系統或框架中的錯誤。 – 2012-08-03 16:58:22
當您使用MSDN示例時,您的控制檯輸出如何:http://msdn.microsoft.com/en-us/library/dd782932.aspx – CrashCodes 2012-08-03 18:23:28