我有一个文件,n
对象的实例被序列化并存储在其中。
在某些情况下,我需要跳过存储的记录并读入k 2k 3k ... n
序列而不是正常的1 2 3 ... n
序列。由于这些实例的长度不同,我编写此代码以跳过记录,但它会抛出Invalid wire-type exception
。 (例外有this question的链接,但没有帮助)
这只是一个简单的错误,还是我以错误的方式做错了?
long position = stream.Position;
int length = 0;
for (int i = 0; i < skipRate; ++i)
{
Serializer.TryReadLengthPrefix(stream, PrefixStyle.Fixed32, out length);
position += length;
stream.Position = position;
Console.WriteLine("Skipped " + length + " bytes");
}
MYCLASS retval = Serializer.DeserializeWithLengthPrefix<MYCLASS>(stream, PrefixStyle.Fixed32, 1);
修改
long position = stream.Position;
int length;
for (int i = 0; i < skipRate; ++i)
{
Serializer.TryReadLengthPrefix(stream, PrefixStyle.Fixed32, out length);
length += (int)(stream.Position - position); // add number of bytes that TryReadLengthPrefix moves stream
stream.Position = position; // Rewind
Serializer.DeserializeWithLengthPrefix<SimulationOutputData>(stream, PrefixStyle.Fixed32, 1);
Console.WriteLine("Try read returns " + length + ", but deserialize goes on " + (stream.Position-position));
}
输出:
Try read returns 1209, but deserialize goes on 1209
Try read returns 1186, but deserialize goes on 1186
Try read returns 1186, but deserialize goes on 1186
Try read returns 1186, but deserialize goes on 1186
Try read returns 1186, but deserialize goes on 1186
Try read returns 1209, but deserialize goes on 1209
Try read returns 1167, but deserialize goes on 1167
.
.
.
此代码有效(为什么?!!有什么区别?):
Serializer.TryReadLengthPrefix(stream, PrefixStyle.Fixed32, out length);
length += (int)(stream.Position - position);
stream.Position = position;
position += length;
stream.Position = position;
答案 0 :(得分:2)
athabaska(评论)有它的要点。您的position
增量不计入标题。一个简洁的实现可能是:
for (int i = 0; i < skipRate; ++i)
{
int length;
if(!Serializer.TryReadLengthPrefix(stream, PrefixStyle.Fixed32, out length))
{
throw new EndOfStreamException(); // not enough records
}
s.Seek(length, SeekOrigin.Current);
}
MYCLASS retval = Serializer.DeserializeWithLengthPrefix<MYCLASS>(
stream, PrefixStyle.Fixed32, 0);