0

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?

3
  • 1
    There is no reason to do this. Commented May 22, 2011 at 22:37
  • 1
    ALL-CAPS titles are extremely annoying. Commented May 22, 2011 at 22:39
  • 1
    @Slaks nice link mate :) Commented May 22, 2011 at 22:41

3 Answers 3

5

Just use

System.IO.File.WriteAllText(fileName, textBox1.Text);

and

textBox1.Text = System.IO.File.ReadAllText(fileName);
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.