我正在尝试对字符串进行序列化/反序列化。使用以下代码:
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"