c# - 字符串序列化和反序列化问题

标签 c# serialization

我正在尝试序列化/反序列化字符串。使用代码:


       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));
        } <p></p>

<p></p>

如果我使用字符串变量,这两段代码工作正常。

但是如果我反序列化一个字符串并将其保存到一个文件中,在读取后面并再次序列化它之后,我最终只得到字符串的第一部分。 所以我相信我的文件保存/读取操作有问题。这是我保存/读取的代码


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"

最佳答案

就用

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

并且不要忘记在您的 using 语句中添加 System.Text

顺便说一句,为什么你需要序列化一个字符串并以这种方式保存它? 您可以只使用 File.WriteAllText() 或 File.WriteAllBytes。与您可以读回的方式相同,File.ReadAllBytes() 和 File.ReadAllText()

关于c# - 字符串序列化和反序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5173033/

相关文章:

c# - 将数组初始化为动态大小 - C#

c# - 快速功能可根据键返回字符串,反之亦然

c# - 使用 ApplicationSettingsBase 存储通用 List<CustomObject>

python - 使用混合 Django 模型和字典的 Django JSON 序列化

python - 压缩序列化 Python 数据最节省空间的方法是什么?

c# - Mac OS X Lion 上的屏幕捕获程序,最好在其他操作系统上可移植

c# - libtidy .NET 包装器 html5

php - 序列化字符串中的偏移错误没有意义

php - 限制 unserialize() 返回数组?

c# - 将字符串拆分为子字符串以节省大空间