【问题标题】:Convert FileStream.ReadByte() returned int to byte?将 FileStream.ReadByte() 返回的 int 转换为字节?
【发布时间】:2018-09-17 05:04:28
【问题描述】:

我需要读取文件中的所有原始字节,然后将它们发送到字节流中。我的问题是 FileStream.ReadByte() 返回一个 int。我无法将其转换为字节。例如:

FileStream fStream = new FileStream(filePath);
byte readByte = Convert.ToByte(fStream.ReadByte()); // Throws converted value too large for unsigned byte exception!
byteBuffer[index] = readByte; // Need the raw byte for this byte buffer.

如何在 C# 中解决这个问题?

谢谢,周末愉快!

【问题讨论】:

    标签: type-conversion int byte filestream


    【解决方案1】:

    ReadByte 返回字节,转换为 Int32,如果已到达流的末尾,则返回 -1。当返回 -1 无法转换为字节时,您会在文件末尾收到异常。 所以只需检查它,例如

    var tmp = fStream.ReadByte();
    if (tmp == -1)
        // end of file reading
    else 
        byteBuffer[index] = Convert.ToByte(tmp);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-06-22
      • 2011-11-16
      • 2011-03-07
      • 2016-03-04
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多