开发者

Deserialize binary file to string

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 stri开发者_运维百科ng of the stream. The rest of the stream did not show up. How should I fix this?


Just use

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

and

textBox1.Text = System.IO.File.ReadAllText(fileName);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜