如何为C# Windows Forms记事本应用添加持久化保存与恢复功能?
实现WinForms记事本的笔记持久化(无需数据库)
1. 定义笔记数据类
先创建一个简单的类来封装单条笔记的标题和内容,方便后续序列化操作:
public class Note { public string Title { get; set; } public string Content { get; set; } }
2. 关闭应用时保存笔记
在窗体的FormClosing事件中,把DataGridView里的所有笔记导出为JSON文件,存在程序目录下:
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { List<Note> notes = new List<Note>(); foreach (DataGridViewRow row in dataGridViewNotes.Rows) { // 跳过DataGridView的最后一行空行(如果允许用户新增行) if (!row.IsNewRow) { notes.Add(new Note { Title = row.Cells["TitleColumn"].Value?.ToString() ?? "", Content = row.Cells["ContentColumn"].Value?.ToString() ?? "" }); } } // 序列化并写入文件 string json = JsonSerializer.Serialize(notes); string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "notes.json"); File.WriteAllText(savePath, json); }
注意:把代码里的TitleColumn和ContentColumn换成你DataGridView实际的列名,或者用列索引(比如row.Cells[0])
3. 启动应用时加载笔记
在窗体的Load事件中,读取之前保存的JSON文件,把数据填充回DataGridView:
private void MainForm_Load(object sender, EventArgs e) { string savePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "notes.json"); if (File.Exists(savePath)) { string json = File.ReadAllText(savePath); List<Note> notes = JsonSerializer.Deserialize<List<Note>>(json) ?? new List<Note>(); dataGridViewNotes.Rows.Clear(); foreach (var note in notes) { dataGridViewNotes.Rows.Add(note.Title, note.Content); } } }
必要的引用
在代码文件顶部添加这些using指令:
using System.Collections.Generic; using System.IO; using System.Text.Json; using System.Reflection;
额外提示
- 如果你的DataGridView开启了
AllowUserToAddRows,必须跳过最后一行空行,否则会保存无效的空笔记。 - 这个方案完全不需要数据库,所有数据存在本地的
notes.json文件里,打开程序目录就能找到,适合新手快速实现持久化需求。
内容的提问来源于stack exchange,提问作者I_Cant_Code
相关产品推荐
相关产品推荐

