I want to save a struct of 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.
-
3Can you elaborate on your "i want implement this action like implement it in c and c++ language" comment? Serialization and deserialization is the standard way of doing this in .NET, so I am a bit surprised to hear that you're not interested in serialization.JeffFerguson– JeffFerguson2010-01-02 01:32:36 +00:00Commented Jan 2, 2010 at 1:32
-
I'd guess his C way is fwrite(file, &data, 1, sizeof (data)) and C++ way is file.write(&data, sizeof data)Ben Voigt– Ben Voigt2010-01-02 02:15:05 +00:00Commented Jan 2, 2010 at 2:15
-
@JeffFerguson Serialization is not necessary in C++ and Delphi.SHIN JaeGuk– SHIN JaeGuk2022-10-11 07:02:57 +00:00Commented Oct 11, 2022 at 7:02
3 Answers
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.
Comments
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).
Comments
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.