代码之家  ›  专栏  ›  技术社区  ›  Amit

流.read方法接受长度作为整数类型???作为

  •  2
  • Amit  · 技术社区  · 14 年前

    我正在尝试从流中读取文件。

    我正在使用流.read方法读取字节。代码如下所示

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

    上面的错误是因为最后一个参数outputMessage.FileByTestStream.Length文件“返回一个长类型值,但该方法需要整数类型。

    1 回复  |  直到 14 年前
        1
  •  4
  •   David Hoerster    14 年前

    把它转换成整数。。。

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

    如果您正在读取的数据大小不合理,您可能需要考虑循环将数据读入缓冲区(例如 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 循环一次。