11 Temmuz 2018

C# Serializable Özelliği ile Nesneleri Dosyaya Yazmak ve Okumak

using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace SerializeDemo
{
    class Program
    {
        
        static void Main(string[] args)
        {
            string dbPath = "serialize_demo.dat";
            List employees;
            if (File.Exists(dbPath))
                using (var fs = new FileStream(dbPath, FileMode.Open, FileAccess.Read))
                {
                    var formatter = new BinaryFormatter();
                    employees = (List)formatter.Deserialize(fs);
                }
            else
                using (var fs = new FileStream(dbPath, FileMode.Create, FileAccess.Write))
                {
                    employees = CreateExampleList();
                    var formatter = new BinaryFormatter();
                    formatter.Serialize(fs, employees);
                }
        }

        public static List CreateExampleList()
        {
            return new List()
            {
                new Employee
                {
                    Id = 1,
                    Name = "Test 1",
                    Birthdate = DateTime.Now,
                    Salary = 1m
                },
                new Employee
                {
                    Id = 2,
                    Name = "Test 2",
                    Birthdate = DateTime.Now,
                    Salary = 1.3m
                }
            };
        }
    }
    [Serializable]
    public class Employee
    {
        public int Id { get; set; }

        public string Name { get; set; }
        public decimal Salary { get; set; }
        public DateTime Birthdate { get; set; }
    }
}