I want to save a struct of开发者_如何学C data in a file in C#, but I don't want to use serialize and deserialize to implement it. I want implement this action like I implement it in the C and C++ languages.
System.IO - File and Streams
To implement it in the "old fashioned way" in C#/.NET, based on the assumption C++ might use raw files and streams, you need to start in the .NET Framework's System.IO
namespace.
Note: This allows you complete customization over the file reading/writing process so you don't have to rely on implicit mechanisms of serialization.
Files can be managed and opened using System.IO.File and System.IO.FileInfo to access Streams. (See the inheritance hierarchy at the bottom of that page to see the different kinds of streams.)
Helper Classes
So you don't have to manipulate bits and bytes directly (unless you want to).
For binary file access you can use System.IO.BinaryReader and BinaryWriter. For example, it easily converts between native data types and stream bytes.
For text-based access file access use System.IO.StreamReader and StreamWriter. Let's you use strings and characters instead of worrying about bytes.
Random Access
If random access is supported on the stream, use a method such as Stream.Seek(..) to jump around based on on whatever algorithm you decide on for determining record lengths and such.
You can use PtrToStructure and StructureToPtr to just dump the content to/from untyped data in a byte array which you can easily push to the file as one block. Just don't try this if your structure contains references to other objects (try keeping indexes instead, perhaps).
If you don't want to serialize it, you can always just use a BitConverter to convert the members to bytes via GetBytes, and write these directly to a Stream.
精彩评论