我必须将对象写入二进制文件。我的结构看起来像这样。
Struct Company
{
int numberofemployees
list of Struct Employee.
}
Struct Employee
{
string EmployeeName;
string Designation;
}
进行上述操作的最佳方法是什么? 问候 拉朱
答案 0 :(得分:9)
据我了解,BinaryFormatter是这项工作的工具。
编辑:正如Marc在评论中解释的那样,BinaryFormatter有一些缺点。他在博客中推荐protobuf-net。
答案 1 :(得分:7)
您希望输出到底是什么样的?你可以手动编写它(参见Lirik的答案),或者如果你想要运行时支持,可能就像protobuf-net那样。
如果您正在使用类(我希望您确实应该这样做),这将是微不足道的,但另外protobuf-net v2(目前仅作为源提供)应该与“原样”一起使用。
有关信息,我将按以下方式进行操作:
public class Company
{
private readonly List<Employee> employees = new List<Employee>();
public List<Employee> Employees { get { return employees;}}
}
public class Employee
{
public string EmployeeName {get;set;}
public string Designation {get;set;}
}
这可以使用序列化属性进行修饰,或者(再次使用protobuf-net v2)像这样的测试(通过):
[Test]
public void CanSerializeCompany()
{
var model = TypeModel.Create();
model.Add(typeof(Company), false).Add("Employees");
model.Add(typeof(Employee), false).Add("EmployeeName", "Designation");
model.CompileInPlace();
Company comp = new Company {
Employees = {
new Employee { Designation = "Boss", EmployeeName = "Fred"},
new Employee { Designation = "Grunt", EmployeeName = "Jo"},
new Employee { Designation = "Scapegoat", EmployeeName = "Alex"}}
}, clone;
using(var ms = new MemoryStream()) {
model.Serialize(ms, comp);
ms.Position = 0;
Console.WriteLine("Bytes: " + ms.Length);
clone = (Company) model.Deserialize(ms, null, typeof(Company));
}
Assert.AreEqual(3, clone.Employees.Count);
Assert.AreEqual("Boss", clone.Employees[0].Designation);
Assert.AreEqual("Alex", clone.Employees[2].EmployeeName);
}
(并写入46个字节)
应该使用私有字段,结构等 - 我必须看看......
如果您能够添加属性,则无需手动设置模型(前4行)。其余代码只显示完整的往返使用情况。
答案 2 :(得分:6)
Here is an example如何读取/写入二进制文件:
using System;
using System.IO;
public class BinaryFileTest {
private static void Main() {
FileStream fs = new FileStream("test.dat", FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
w.Write(1.2M);
w.Write("string");
w.Write("string 2");
w.Write('!');
w.Flush();
w.Close();
fs.Close();
fs = new FileStream("test.dat", FileMode.Open);
StreamReader sr = new StreamReader(fs);
Console.WriteLine(sr.ReadToEnd());
fs.Position = 0;
BinaryReader br = new BinaryReader(fs);
Console.WriteLine(br.ReadDecimal());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadString());
Console.WriteLine(br.ReadChar());
fs.Close();
}
}