I have a question regarding deserialization using Protobuf .Net. I am trying to replace XMLSerializer with it and I cannot find a way to deserialize single field from file.
I need information if file was modified, which is one of the fields in saved structure.
Is it even possible ? If yes, can I ask for some help?
Regards
In most cases, frankly you can just deserialize the entire thing – it’ll be fast, etc. However, if you really want to limit it, there are a few options.
The simplest is to just create a smaller model, with just the information you want on it. So: if your original model has 46 fields on it, 5 of which are collections etc – but you just want the
Versionwhich is in field 12, then:now deserialize that:
This will work because protobuf-net is contract based; it doesn’t have to be exactly the same type, as long as it looks close enough. A more advanced approach, though, would be to use
ProtoReader:The reason you might want to use the above is that it can stop looking earlier – i.e. as soon as we have found our field 12, we can kill the reader without processing the rest of the file. Normally, I would only use the second approach if we know the data is large, and we don’t want much of it.
There is a slight gotcha in that technically protobuf is an appendable format, so in theory there could be another “field 12” right at the end of the file. By the speficication, it is “last value wins”, so short-circuiting in the above could (in theory) give you a different answer. HOWEVER! This is very very unlikely, and you would usually know if you are taking advantage of appended messages. This simply DOES NOT APPLY to most people.