Click here to Skip to main content
15,936,565 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
myclass hd has 2 members, string1 and string2. I want to send the myclass data to a file test.dat using BinaryFormatter.
I could not
if BinaryFormatter is obsolete. Please let me know the alternative.

What I have tried:

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

        BinaryFormatter formatter = new BinaryFormatter();
        FileStream output;

//hd is a class filled from 2 textBox
output = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.Write);
formatter.Serialize(output, hd);
Updated 28-Aug-23 9:14am
[no name] 27-Aug-23 14:48pm    
You should be focusing on the class you're trying to serialize (other than simply "commenting" that it "exists" somewhere).

1 solution

BinaryFormatter is obsolete, and as the documentation clearly says, you shouldn't be using it in new projects: BinaryFormatter.Serialize Method (System.Runtime.Serialization.Formatters.Binary) | Microsoft Learn[^]

This suggests some alternatives: Deserialization risks in use of BinaryFormatter and related types | Microsoft Learn[^]

If there is a reason why you absolutely need a binary output (compatibility with some other software or hardware for example) then this may help: ByteArrayBuilder - A StringBuilder for Bytes[^]
Share this answer
Engineer khalid 28-Aug-23 6:05am    
i used binaryWriter and BinaryReader instead .it seems i will have a question about class size ,i might post it later

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900