3

I'm trying to serialize/deserialize string. Using the code:


       private byte[] StrToBytes(string str)
       {
            BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(); bf.Serialize(ms, str); ms.Seek(0, 0); return ms.ToArray(); } private string BytesToStr(byte[] bytes) { BinaryFormatter bfx = new BinaryFormatter(); MemoryStream msx = new MemoryStream(); msx.Write(bytes, 0, bytes.Length); msx.Seek(0, 0); return Convert.ToString(bfx.Deserialize(msx)); }

This two code works fine if I play with string variables.

But If I deserialize a string and save it to a file, after reading the back and serializing it again, I end up with only first portion of the string. So I believe I have a problem with my file save/read operation. Here is the code for my save/read


private byte[] ReadWhole(string fileName)
        {
            try
            {
                using (BinaryReader br = new BinaryReader(new FileStream(fileName, FileMode.Open)))
                {
                   return br.ReadBytes((int)br.BaseStream.Length);
                }
} catch (Exception) { return null; }
} private void WriteWhole(byte[] wrt,string fileName,bool append) { FileMode fm = FileMode.OpenOrCreate; if (append) fm = FileMode.Append; using (BinaryWriter bw = new BinaryWriter(new FileStream(fileName, fm))) { bw.Write(wrt); } return; }

Any help will be appreciated. Many thanks

Sample Problematic Run:


WriteWhole(StrToBytes("First portion of text"),"filename",true);
WriteWhole(StrToBytes("Second portion of text"),"filename",true);
byte[] readBytes = ReadWhole("filename");
string deserializedStr = BytesToStr(readBytes); // here deserializeddStr becomes "First portion of text"
AFgone
  • 1,172
  • 4
  • 16
  • 31

2 Answers2

5

Just use

Encoding.UTF8.GetBytes(string s) 
Encoding.UTF8.GetString(byte[] b)

and don't forget to add System.Text in your using statements

BTW, why do you need to serialize a string and save it that way? You can just use File.WriteAllText() or File.WriteAllBytes. The same way you can read it back, File.ReadAllBytes() and File.ReadAllText()

Davita
  • 8,928
  • 14
  • 67
  • 119
  • thanks for reply. But I am trying to serialize since I don't want end-user to see file content, since it contains some private configuration data, which should not be seen by end-user. Your code works but with this I have the plain text which I do not prefer – AFgone Mar 02 '11 at 20:52
  • 1
    use Encoding.UTF8.GetBytes(string s //FileContent); You will receive an array of bytes which is not readable. You can also encrypt your string. take a look http://stackoverflow.com/questions/202011/encrypt-decrypt-string-in-net – Davita Mar 02 '11 at 21:17
0

The problem is that you are writing two strings to the file, but only reading one back.

If you want to read back multiple strings, then you must deserialize multiple strings. If there are always two strings, then you can just deserialize two strings. If you want to store any number of strings, then you must first store how many strings there are, so that you can control the deserialization process.

If you are trying to hide data (as indicated by your comment to another answer), then this is not a reliable way to accomplish that goal. On the other hand, if you are storing data an a user's hard-drive, and the user is running your program on their local machine, then there is no way to hide the data from them, so this is as good as anything else.

Jeffrey L Whitledge
  • 58,241
  • 9
  • 71
  • 99