c# 检查 MemoryStream 中是否有 '\0' 值的字符
c# Check MemoryStream for char with '\0' value
ok之前代码这里是瘦的:
我正在开发一个从游戏客户端读取二进制文件的工具,这个二进制文件包含许多字段(115),但重要的是文件(db_item.rdb)存储在一个区域中的所有字符串256 字节。大多数这些字符串的长度都小于 10,因此在 26k 行中每行处理 24 次约 240 个空字节。 (别怪我这么烂的设计,游戏不是我做的:P)
因此,对于我处理的每个字段,我调用一个方法 readStream(),它读取我之前通过加载前面提到的 .rdb 创建的 MemoryStream
目前我读取这个文件的执行时间 (db_item.rdb) 是 2-2.2s,大部分时间花在 readStream() (~740ms)
编辑:澄清问题:
是否可能?如果可能,如何读取内存流直到遇到空白字符 ('\0')?还是内存流根本不适合这样的任务?
像这样的东西可以工作。但是,取决于流的长度,不确定这是否会对处理时间产生很大影响。
这使用了 MemoryStream.ReadByte Method()
Return Value
Type: System.Int32
The byte cast to a Int32, or -1 if the end of the stream has been reached.
Remarks
If the read operation is successful, the current position within the
stream is advanced by one byte. If an exception occurs, the current
position within the stream is unchanged.
private static byte[] readStream(MemoryStream ms, int size)
{
byte[] buffer = new byte[size];
if (size != 256)
ms.Read(buffer, 0, buffer.Length);
else
{
for (int i = 0; i < 256; i++)
{
byte b;
var r = ms.ReadByte();
if (r < 0) //read byte returns -1 if at end of stream
break;
b = (byte)r;
if (b == '[=10=]') //equals our empty flag
break;
buffer[i] = b;
}
}
return buffer;
}
ok之前代码这里是瘦的:
我正在开发一个从游戏客户端读取二进制文件的工具,这个二进制文件包含许多字段(115),但重要的是文件(db_item.rdb)存储在一个区域中的所有字符串256 字节。大多数这些字符串的长度都小于 10,因此在 26k 行中每行处理 24 次约 240 个空字节。 (别怪我这么烂的设计,游戏不是我做的:P)
因此,对于我处理的每个字段,我调用一个方法 readStream(),它读取我之前通过加载前面提到的 .rdb 创建的 MemoryStream
目前我读取这个文件的执行时间 (db_item.rdb) 是 2-2.2s,大部分时间花在 readStream() (~740ms)
编辑:澄清问题:
是否可能?如果可能,如何读取内存流直到遇到空白字符 ('\0')?还是内存流根本不适合这样的任务?
像这样的东西可以工作。但是,取决于流的长度,不确定这是否会对处理时间产生很大影响。
这使用了 MemoryStream.ReadByte Method()
Return Value
Type: System.Int32
The byte cast to a Int32, or -1 if the end of the stream has been reached.
Remarks
If the read operation is successful, the current position within the stream is advanced by one byte. If an exception occurs, the current position within the stream is unchanged.
private static byte[] readStream(MemoryStream ms, int size)
{
byte[] buffer = new byte[size];
if (size != 256)
ms.Read(buffer, 0, buffer.Length);
else
{
for (int i = 0; i < 256; i++)
{
byte b;
var r = ms.ReadByte();
if (r < 0) //read byte returns -1 if at end of stream
break;
b = (byte)r;
if (b == '[=10=]') //equals our empty flag
break;
buffer[i] = b;
}
}
return buffer;
}