- [C#] Di chuyển và thay đổi kích thước Control Winform khi ứng dụng đang chạy
- [VB.NET] Chia sẻ source tạo sắp xếp đội hình bóng đá Line-ups đội bóng
- [C#] Hướng dẫn chỉnh sửa Text của label trực tiếp trên winform
- [C#] Hướng dẫn custom TextBox giống Ultraviewer trên Winform
- [C#] Show Modal Winform like Bootstrap
- [DATABASE] Thứ tự thực hiện mệnh đề truy vấn SELECT trong Sqlserver
- [C#] Hướng dẫn viết addin Excel Lấy hình ảnh từ URL internet vào Excel
- [DATABASE] TSQL view max length all column data trên table Sqlserver
- [DEVEXPRESS] Hướng dẫn sử dụng MailMerge kèm Hình ảnh trên Winform
- [DATABASE] Hướng dẫn truy vấn xem kích thước lưu trữ của từng bảng ghi Table trên sqlserver
- [C#] Hướng dẫn Fake Date Time sử dụng thư viện Harmony
- [DATABASE] Phân biệt câu lệnh DDL và DML trong sqlserver
- [C#] Hướng dẫn convert file mã HTML sang file Pdf trên winform
- [DEVEXPRESS] Tạo các loại mã vạch Barcode trực tiếp trên Devexpress Barcode API
- [DEVEXPRESS] Hướng dẫn custom Simple button thành Progressbar
- [DATABASE] Tách số và chữ từ chuỗi - hàm tối ưu hóa tách số và chữ trong Sqlserver
- [C#] Tìm kiếm gần đúng Full Text Search sử dụng thư viện Lucene.NET
- [C#] Chia sẻ tài liệu, sdk và source code máy chấm công dòng máy ZKTeco
- [C#] Memory Cache là gì, và sử dụng trong ứng dụng Winform
- [DATABASE] Khóa chính Primary Key trong Sqlserver
[C#] Hướng dẫn lưu List Object thành tập tin file nhị phân Binary
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
Kết quả sau khi các bạn lưu thành file nhị phân và mở bằng Notepad như sau:
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!