2010-08-30 37 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

相关问题