I want to store a string in a file in a way, that it can't be (easily) read. So I use a BinaryFormatter like this:
using (FileStream fs = File.Create(sfDialog.FileName, 2048, FileOptions.None))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, Encoding.Unicode.GetBytes(this.BodyText));
}
where this.BodyText
is the string to save.
Now I'm struggling to read it back from the file. I tried BinaryReader
without success, so I guess, I have to use a BinaryFormatter
. I tried the Deserialize
method, but it returns an object which can´t be cast to a string. Also Convert.ToBase64String
can't be used on an object.
Does anyone know how to solve my problem?
I agree with the others, you should be using some proper encryption instead of this.
But to answer your actual question: You are serializing a byte array. So that's what you get when you deserialize it.
So, after deserializing, cast to byte[]
and convert this byte array to a string:
var s = Encoding.Unicode.GetString((byte[])deserializedValue);