Reputation: 375
How do I deserialize a binary file to a string
?
This is my sample code so far:
public function serialize()
{
FileStream fs = new FileStream("test.txt", FileMode.Append);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, textBox1.Text);
fs.Flush();
fs.Close();
}
public function deserialize()
{
FileStream fs = File.Open(openFileDialog1.FileName, FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
richTextBox1.Text = formatter.Deserialize(mystream) as string;
fs.Flush();
fs.Close();
}
When I start to debug the application, it only shows the first string of the stream. The rest of the stream did not show up. How should I fix this?
Upvotes: 0
Views: 1401
Reputation: 7452
The right way to do this is to put all of the values that you want to serialize into a serializable structure and then serialize that structure. On the other end you deserialize that structure and then put the values where they need to go.
Note that the binary serializer produces binary, not text output. If you want human readable serialized data you can use the XmlSerializer instead.
Upvotes: 2
Reputation: 273844
Just use
System.IO.File.WriteAllText(fileName, textBox1.Text);
and
textBox1.Text = System.IO.File.ReadAllText(fileName);
Upvotes: 5
Reputation: 888203
Binary serialization serializes object graphs; it doesn't just write strings.
It wouldn't make sense to combine object graphs.
You should read and write the file directly using the File
class.
Upvotes: 0