Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# writing object to binary file

Tags:

c#

.net

I have to write an object in to binary file.My struct looks like this.

   Struct Company
    {
       int numberofemployees
       list of Struct Employee.
    }

    Struct Employee
    {
       string EmployeeName;
       string Designation;
    }

What is the best way to do the above operation? Regards Raju

like image 457
user209293 Avatar asked Apr 08 '10 09:04

user209293


People also ask

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C language used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...


2 Answers

In my understanding, BinaryFormatter is the tool for this job.

Edit: As Marc explains in the comments, BinaryFormatter has certain disadvantages. He recommends protobuf-net in his blog.

like image 147
Jens Avatar answered Oct 04 '22 00:10

Jens


What exactly do you want the output to look like? You can write it manually (see Lirik's answer), or if you want runtime support, perhaps something like protobuf-net.

This would be trivial to do if you were using classes (which I expect you actually should be), but additionally protobuf-net v2 (only available as source at the moment) should work with that "as is".

For info, here is how I would do it as classes:

    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;}
    }

This could be decorated with serialization attributes, or (again, using protobuf-net v2) something like this test (which passes):

    [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);
    }

(and writes 46 bytes)

It should work with private fields, structs, etc - I'd have to take a look...

If you are able to add attributes, then you don't need to set up the model manually (the first 4 lines). The rest of the code is just showing full round-trip usage.

like image 26
Marc Gravell Avatar answered Oct 03 '22 23:10

Marc Gravell