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