简体   繁体   中英

Binary Serialization in C# - Append to a file

I'm doing a project where I'm recording user inputs to a list and serializing this information to a binary file. So far I can record the users inputs on a gamepad in a LIST of padStates and the serialize this information but at the minute it will only serialize AFTER the session has ended. In other words, I have to have the padstate LIST in memory for the entire time that the recording is running. Obviously this isn't ideal since I'm taking up memory and when it gets too big it will crash the program.

I was thinking it might be possible to open a filestream when a class is instantiated and periodically write the LIST to a file; say every 600 frames or so. Once this is serialized I can then clear the list and start populating it again.

Is this actually possible? I guess it's appending data to the file but none of the books I have talk about this..

If anyone can point me in the direction that'd be great.

Appending data to a file is done using FileMode.Append.

This can be specified when constructing a FileStream object.

FileStream Constructor

you can use a FileStream to append data to an existing file. There's an example in the linked MSDN article.

The other part of your question, about when you should do this, is really up to your implementation. I would also recommend that you do the logging in the file asynchronously, so the app doesn't block.

Why append to a binary file? Appending is not going to work. It will be impossible to read the data properly -- appending is the realm of text files.

So append to a text file, that will work fine, as in this example:

http://msdn.microsoft.com/en-us/library/3zc0w663.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM