Mil*_*vić 3 .net c# binaryreader
我使用下面的代码序列化的数据,从数据表。
var rows = new List<Dictionary<string, object[]>>();
Run Code Online (Sandbox Code Playgroud)
我从数据表中填写的行并将它们放在字典。不要问为什么:)
using(var fileStream = new FileStream(@"D:\temp.bin", FileMode.Create, FileAccess.Write, FileShare.None))
using(var bw = new BinaryWriter(fileStream))
{
foreach(Dictionary<string, object[]> row in rows)
{
byte[] bytes = ObjectToByteArray(row);
bw.Write(bytes);
}
}
Run Code Online (Sandbox Code Playgroud)
随着下面的方法:
private static byte[] ObjectToByteArray(Dictionary<string, object[]> rows)
{
var bf = new BinaryFormatter();
using(var ms = new MemoryStream())
{
bf.Serialize(ms, rows);
return ms.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图做的是逐行反序列化,如果使用BinaryReader可以的话。问题是,我坚持只读取第一行。
我想实现的是:
using(BinaryReader reader = new BinaryReader(File.Open(@"D:\temp.bin", FileMode.Open)))
{
int pos = 0;
int length = (int)reader.BaseStream.Length;
while(pos < length)
{
byte[] v = reader.ReadBytes(pos);
Dictionary<string, object[]> row = FromByteArray(v);
// Advance our position variable.
pos += row.Count;
}
}
Run Code Online (Sandbox Code Playgroud)
最大的问题是reader.ReadBytes(XXX) - >值应该是读什么?我不提前知道。我需要阅读整条生产线,并转换为词典。我用于转换回来的方法是:
public static Dictionary<string, object[]> FromByteArray(byte[] data)
{
BinaryFormatter bf = new BinaryFormatter();
using(MemoryStream ms = new MemoryStream(data))
{
object obj = bf.Deserialize(ms);
return (Dictionary<string, object[]>)obj;
}
}
Run Code Online (Sandbox Code Playgroud)
正如我所说FromByteArray工作正常的第一线,我没有发现任何方式来阅读下一行。
当我使用BinarryFormatter连载完整的文件,它传递如果文件没有那么大。如果是OOM发生。同样代表反序列化。这就是为什么我要它部分地进行序列化/反序列化。
尝试了一切,到处搜索。由于在这一个帮助。
对于每次迭代保存文件还包括以下序列化对象的长度英寸
读取时,每次迭代都首先读取4字节(reader.ReadInt32)以获取此值,并读取此字节以进行反序列化。
我想应该是这样的:
using(var fileStream = new FileStream(@"D:\temp.bin", FileMode.Create, FileAccess.Write, FileShare.None))
{
using(var bw = new BinaryWriter(fileStream))
{
foreach(Dictionary<string, object[]> row in rows)
{
byte[] bytes = ObjectToByteArray(row);
bw.Write(bytes.Length);
bw.Write(bytes);
}
}
}
using(BinaryReader reader = new BinaryReader(File.Open(@"D:\temp.bin", FileMode.Open)))
{
int length = (int)reader.BaseStream.Length;
while(reader.BaseStream.Position != length)
{
int bytesToRead = reader.ReadInt32();
byte[] v = reader.ReadBytes(bytesToRead);
Dictionary<string, object[]> row = FromByteArray(v);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3142 次 |
| 最近记录: |