首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# WinForm 學生信息管理:無數據庫文件存儲方案

     編輯:程式設計疑難解答

需求分析

學生信息:學號、姓名、性別。無數據庫要求,數據持久化到本地文件,啟動時加載。

方案選型

格式優點缺點適用場景
JSON (Newtonsoft.Json / System.Text.Json)結構化、可讀、支持層級、標準庫頻繁寫入需整文件覆蓋配置、小數據量、跨平台
CSVExcel 可直接打開、極簡單無類型、逗號轉義麻煩導出報表、數據交換
二進制序列化 (BinaryFormatter / Protobuf)體積小、速度快不可讀、版本兼容難高性能、內部存儲
XML自描述、Schema 驗證冗長、解析慢舊系統兼容

推薦:JSON,現代 .NET 核心庫 System.Text.Json 無需第三方依賴。

實體類設計

public class Student {
    public string StudentId { get; set; }
    public string Name { get; set; }
    public string Gender { get; set; }
    public override string ToString() => $"{StudentId}\t{Name}\t{Gender}";
}

數據訪問層 (DAL) 封裝

using System.Collections.Generic;
using System.IO;
using System.Text.Json;

public class StudentRepository {
    private readonly string _filePath = "students.json";
    private List<Student> _cache;

    public StudentRepository() {
        Load();
    }

    public List<Student> GetAll() => new List<Student>(_cache);

    public void Add(Student s) {
        if (_cache.Any(x => x.StudentId == s.StudentId))
            throw new ArgumentException("學號已存在");
        _cache.Add(s);
        Save();
    }

    public bool Remove(string id) {
        var s = _cache.FirstOrDefault(x => x.StudentId == id);
        if (s == null) return false;
        _cache.Remove(s);
        Save();
        return true;
    }

    public bool Update(Student s) {
        var idx = _cache.FindIndex(x => x.StudentId == s.StudentId);
        if (idx < 0) return false;
        _cache[idx] = s;
        Save();
        return true;
    }

    private void Load() {
        if (!File.Exists(_filePath)) {
            _cache = new List<Student>();
            return;
        }
        string json = File.ReadAllText(_filePath);
        _cache = JsonSerializer.Deserialize<List<Student>>(json) ?? new List<Student>();
    }

    private void Save() {
        var options = new JsonSerializerOptions { WriteIndented = true };
        string json = JsonSerializer.Serialize(_cache, options);
        File.WriteAllText(_filePath, json);
    }
}

WinForm 界面綁定

public partial class MainForm : Form {
    private readonly StudentRepository _repo = new StudentRepository();
    private BindingSource _binding = new BindingSource();

    public MainForm() {
        InitializeComponent();
        _binding.DataSource = _repo.GetAll();
        dataGridView1.DataSource = _binding;
    }

    private void btnAdd_Click(object sender, EventArgs e) {
        var s = new Student { StudentId = txtId.Text, Name = txtName.Text, Gender = cbGender.Text };
        try { _repo.Add(s); RefreshGrid(); } 
        catch (Exception ex) { MessageBox.Show(ex.Message); }
    }

    private void btnDelete_Click(object sender, EventArgs e) {
        if (dataGridView1.CurrentRow?.DataBoundItem is Student s) {
            _repo.Remove(s.StudentId);
            RefreshGrid();
        }
    }

    private void RefreshGrid() {
        _binding.DataSource = _repo.GetAll();
        dataGridView1.Refresh();
    }
}

進階優化

  • 內存緩存 + 定時保存:高頻操作時避免每次寫磁盤,用 Timer 批量持久化。
  • 並發安全:多窗口操作時,文件鎖 FileShare.None 或遷移至 SQLite(輕量級嵌入式數據庫,單文件,無需安裝)。
  • 異步 IO:await File.WriteAllTextAsync(...) 防止 UI 凍結。

總結

無數據庫小系統,JSON + Repository 模式 + BindingSource 是最清晰、可維護的方案。代碼分層清晰,後續擴展字段、加密、同步極其容易。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved