2010-08-30 71 views
2

我想從流中讀取文件。stream.read方法接受整數類型的長度?作爲

我使用stream.read方法來讀取字節。因此,代碼是這樣下面

FileByteStream.Read(buffer, 0, outputMessage.FileByteStream.Length) 

現在上面給我的錯誤,因爲最後一個參數「outputMessage.FileByteStream.Length」返回一個long類型值,但該方法需要一個整數類型。

請指教。

回答

4

將其轉換爲int ...

FileByteStream.Read(buffer, 0, Convert.ToInt32(outputMessage.FileByteStream.Length))

這可能是一個int,因爲該操作阻塞,直到它完成閱讀...所以如果你在一個高容量的應用程序的時候,你可能不想在您讀入大型文件時阻止。

如果你正在閱讀的是不是合理規模,你可能要考慮循環的數據讀入緩衝區(例如,從MSDN docs):

//s is the stream that I'm working with... 
byte[] bytes = new byte[s.Length]; 
int numBytesToRead = (int) s.Length; 
int numBytesRead = 0; 
while (numBytesToRead > 0) 
{ 
    // Read may return anything from 0 to 10. 
    int n = s.Read(bytes, numBytesRead, 10); 
    // The end of the file is reached. 
    if (n == 0) 
    { 
     break; 
    } 
    numBytesRead += n; 
    numBytesToRead -= n; 
} 

這樣,你不投,如果你選擇一個相當大的數字來讀入緩衝區,那麼你只能通過while循環一次。

+0

+1我只是寫了同樣的帖子... – 2010-08-30 13:34:36

+0

謝謝大家都是冠軍 – Amit 2010-08-30 14:07:52

相關問題