簡體   English   中英

字符串序列化和反序列化問題

[英]string serialization and deserialization problem

我正在嘗試序列化/反序列化字符串。 使用代碼:


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

如果我使用字符串變量,這兩個代碼工作正常。

但是,如果我反序列化一個字符串並將其保存到文件中,在讀完后面並再次序列化之后,我最終只得到字符串的第一部分。 所以我相信我的文件保存/讀取操作有問題。 這是我保存/閱讀的代碼


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; }

任何幫助將不勝感激。 非常感謝

問題運行示例:


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()

問題是你正在為文件寫兩個字符串,但只讀一個。

如果要讀回多個字符串,則必須反序列化多個字符串。 如果總有兩個字符串,那么您可以反序列化兩個字符串。 如果要存儲任意數量的字符串,則必須先存儲有多少字符串,以便控制反序列化過程。

如果您試圖隱藏數據(如您對其他答案的評論所示),那么這不是實現該目標的可靠方法。 另一方面,如果您將數據存儲在用戶的硬盤驅動器中,並且用戶正在本地計算機上運行程序,則無法隱藏數據,因此這與其他任何內容一樣好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM