我正在尝试序列化/反序列化字符串。使用代码:
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));
}
Run Code Online (Sandbox Code Playgroud)
如果我使用字符串变量,那么这两个代码可以正常工作。
但是,如果我反序列化一个字符串并将其保存到文件中,则在阅读了后面的内容并再次对其进行序列化之后,我只会得到字符串的第一部分。所以我相信我的文件保存/读取操作有问题。这是我保存/读取的代码
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;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激。非常感谢
示例问题运行:
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"
Run Code Online (Sandbox Code Playgroud)
只需使用
Encoding.UTF8.GetBytes(string s)
Encoding.UTF8.GetString(byte[] b)
Run Code Online (Sandbox Code Playgroud)
并且不要忘记在using语句中添加System.Text
顺便说一句,为什么您需要序列化字符串并以这种方式保存?您可以只使用File.WriteAllText()或File.WriteAllBytes。以相同的方式读回它,File.ReadAllBytes()和File.ReadAllText()
| 归档时间: |
|
| 查看次数: |
6498 次 |
| 最近记录: |