字符串序列化和反序列化问题

3

我正在尝试对字符串进行序列化/反序列化。使用以下代码:


       private byte[] StrToBytes(string str)
       {
            BinaryFormatter bf = new BinaryFormatter();<br>
            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));
        } 

这两个代码在操作字符串变量时运行良好。
但是,如果我反序列化一个字符串并将其保存到文件中,然后再读取并重新序列化它,最终只得到了字符串的第一部分。因此,我认为我的文件保存/读取操作存在问题。这是我的保存/读取代码:


private byte[] ReadWhole(string fileName)
        {
            try
            {
                using (BinaryReader br = new BinaryReader(new FileStream(fileName, FileMode.Open)))
                {
                   return br.ReadBytes((int)br.BaseStream.Length);
                }<br>
            }
            catch (Exception)
            {
                return null;
            }<br>
        }
        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;
        }

非常感谢你的提问。以下是一个问题样例:


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"

2个回答

5

只需要使用

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

别忘了在你的using语句中添加System.Text。

顺便问一下,为什么需要将字符串序列化并以这种方式保存呢? 你可以使用File.WriteAllText()或File.WriteAllBytes。同样的方法,你也可以读取它,使用File.ReadAllBytes()和File.ReadAllText()


谢谢您的回复。但是我正在尝试序列化,因为我不希望最终用户看到文件内容,因为它包含一些私有配置数据,不应该被最终用户看到。您的代码可以工作,但是这样我得到的是纯文本,而我不喜欢这种方式。 - AFgone
1
使用 Encoding.UTF8.GetBytes(string s //FileContent); 方法可以将字符串转换成字节数组,但该数组是不可读的。您还可以对字符串进行加密。请查看 https://dev59.com/RHVC5IYBdhLWcg3wtzut。 - Davita

0
问题在于您正在将两个字符串写入文件,但只读取了一个字符串。
如果您想要读回多个字符串,则必须反序列化多个字符串。如果始终有两个字符串,则可以反序列化两个字符串。如果您想要存储任意数量的字符串,则必须首先存储有多少个字符串,以便您可以控制反序列化过程。
如果您试图隐藏数据(如您对另一个答案的评论所示),那么这不是实现该目标的可靠方法。另一方面,如果您正在将数据存储在用户的硬盘上,并且用户在本地计算机上运行您的程序,则无法向他们隐藏数据,因此这与其他任何方法一样好。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接