NEWS

[C#] Hướng dẫn lưu List Object thành tập tin file nhị phân Binary

[C#] Hướng dẫn lưu List Object thành tập tin file nhị phân Binary
Đăng bởi: Thảo Meo - Lượt xem: 4876 14:27:32, 15/12/2021PHẦN MỀM

Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn cách lưu trữ List object T xuống dạng File nhị phân trong lập trình C#, winform.

[C#] How to save and load list<T> object to Binary File Winform

binary_list_file_csharp

Kết quả sau khi các bạn lưu thành file nhị phân và mở bằng Notepad như sau:

binary_file_csharp

Thông tin, các bạn hay sử dụng bài này để lưu trữ các cấu hình.

Ở demo trên: 

Mình có một danh sách List<Employee> và mình muốn lưu trữ nó thành dạng file Binary.

Đầu tiên các bạn tạo cho mình một class Employee.cs:

Các bạn nhớ thêm từ khóa [Serializable] trên class Model Employee nhé.

[Serializable]
public class Employee
{
    public int Id { get; set; }
    public string Code { get; set; }
    public string Name { get; set; }
    public string BirthDay { get; set; }
    public string Gender { get; set; }
    public string BirthPlace { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}

Tiếp đến các bạn viết 1 file IOHelper.cs: trong này có hai phương thức save và load list T

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace SaveListObjectToBinaryFile
{
    class IOHelper
    {
        public static void Save<T>(string fileName, List<T> list)
        {           
            try
            {               
                using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                {
                    var formatter = new BinaryFormatter();
                    formatter.Serialize(stream, list);
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public static List<T> Load<T>(string fileName)
        {
            var list = new List<T>();           
            if (File.Exists(fileName))
            {
                try
                {                   
                    using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                    {
                        var formatter = new BinaryFormatter();
                        list = (List<T>)
                            formatter.Deserialize(stream);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

            }
            return list;
        }
    }
}

Source code FormMain.cs

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SaveListObjectToBinaryFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnLoadFile_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "Binary file|*.dat";
            if (dialog.ShowDialog() == DialogResult.OK)
            {                
                var data = IOHelper.Load<Employee>(dialog.FileName);
                dataGridView1.DataSource = data;
            }
        }

        private void btnSaveFile_Click(object sender, EventArgs e)
        {
            var dialog = new SaveFileDialog();
            dialog.Filter = "Binary file|*.dat";
            if(dialog.ShowDialog() == DialogResult.OK)
            {
                var listEmployees = dataGridView1.DataSource as List<Employee>;
                IOHelper.Save(dialog.FileName, listEmployees);
            }
        }

        private async void Form1_Load(object sender, EventArgs e)
        {
            var data = await GetEmployeesAsync();
            dataGridView1.DataSource = data;
        }

        private readonly string URL_API = "https://raw.githubusercontent.com/dinhtona/api-mssql-dapper/main/db.json";
        public Task<List<Employee>> GetEmployeesAsync()
        {
            var task = Task.Run(() => {
                var wc = new WebClient();
                var jData = wc.DownloadString(new Uri(URL_API));

                var employees = JsonConvert.DeserializeObject<List<Employee>>(jData);
                return employees;
            });
            return task;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = null;
        }
    }

Thanks for watching!

DOWNLOAD SOURCE

Tags: binary file c#save list object c#

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn lưu List Object thành tập tin file nhị phân Binary
Đăng bởi: Thảo Meo - Lượt xem: 4876 14:27:32, 15/12/2021PHẦN MỀM