目录一、JSON 序列化 DataGridView 表格展示功能说明完整代码核心知识点二、INI 配置文件读写案例 2两种封装方案1. App.config 全局配置2. 极简工具类 INITool.cs3. 完整底层工具 IniAPI.csTool 公共类库4. 窗体调用示例INI 文件格式规范三、CSV 逗号分隔表格文件案例 3适用场景CSVAPI 完整工具类窗体读取解析逻辑CSV 格式规则四、项目 Settings 用户配置案例 4特点使用步骤底层生成 App.config 配置五、try-catch 异常捕获案例 5核心作用分层捕获规则优先级从上到下标准模板关键字说明六、五种本地存储方案对比七、总结一、JSON 序列化 DataGridView 表格展示功能说明Newtonsoft.Json 反序列化本地 json 文本自定义 DataGridView 列地址文本、图片、alt 提示本地路径加载图片绑定表格 Image 列单元格点击调用系统浏览器打开链接完整代码using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; using Newtonsoft.Json; namespace _1练习 { public partial class Form1 : Form { public Form1() { InitializeComponent(); BindGridView(); BindData(); } // 手动创建DataGridView列不自动生成 private void BindGridView() { dataGridView1.AutoGenerateColumns false; dataGridView1.Columns.Clear(); // 地址文本列 DataGridViewTextBoxColumn colAddr new DataGridViewTextBoxColumn(); colAddr.HeaderText 地址; colAddr.Width 300; colAddr.Name Address; colAddr.DataPropertyName link; dataGridView1.Columns.Add(colAddr); // 图片列 DataGridViewImageColumn colImg new DataGridViewImageColumn(); colImg.HeaderText 图片; colImg.Width 200; colImg.Name proImage; colImg.ImageLayout DataGridViewImageCellLayout.Zoom; colImg.DataPropertyName proImage; dataGridView1.Columns.Add(colImg); // 提示文本列 DataGridViewTextBoxColumn colAlt new DataGridViewTextBoxColumn(); colAlt.HeaderText 提示; colAlt.Width 100; colAlt.Name Alt; colAlt.DataPropertyName alt; dataGridView1.Columns.Add(colAlt); dataGridView1.RowTemplate.Height 80; } // 读取json文件、序列化、加载图片绑定表格 private void BindData() { string jsonText File.ReadAllText(1.txt, System.Text.Encoding.Default); Root root JsonConvert.DeserializeObjectRoot(jsonText); foreach (var item in root.list) { item.proImage Image.FromFile(item.img_url); } dataGridView1.DataSource root.list; } // 单元格点击事件打开网页链接 private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { int addrColIndex dataGridView1.Columns[Address].Index; if (e.ColumnIndex addrColIndex e.RowIndex 0) { string url dataGridView1[addrColIndex, e.RowIndex].Value.ToString(); System.Diagnostics.Process.Start(url); } } } // JSON映射实体 public class ListData { public string link { get; set; } public string img_url { get; set; } public string alt { get; set; } // 内存图片对象仅用于表格展示不序列化存文件 public Image proImage { get; set; } } public class Root { public string title { get; set; } public ListListData list { get; set; } } }核心知识点DataPropertyName绑定实体类属性名实现数据源自动映射单元格DataGridViewImageColumn.ImageLayout.Zoom图片等比缩放适配单元格Process.Start(url)调用系统默认浏览器打开网址Newtonsoft.Json第三方高性能 JSON 序列化库需 NuGet 安装实体分离img_url存文件路径持久化proImage内存图片仅界面展示二、INI 配置文件读写案例 2两种封装方案简易INITool极简封装依赖 AppConfig 读取 ini 文件路径完整IniAPI封装 Windows 原生 kernel32.dll支持增删节点、批量读取、数字 / 浮点读取1. App.config 全局配置?xml version1.0 encodingutf-8 ? configuration startup supportedRuntime versionv4.0 sku.NETFramework,Versionv4.8 / /startup appSettings !-- ini文件物理路径 -- add keyfilePath valueC:\xxx\bin\Debug\config.ini/ /appSettings /configuration2. 极简工具类 INITool.csusing System; using System.Configuration; using System.Runtime.InteropServices; using System.Text; namespace _2_ini文件读写 { public class INITool { // 从配置文件读取ini路径 private static string filePath ConfigurationManager.AppSettings[filePath].ToString(); // 引入Windows原生INI写入API [DllImport(kernel32.dll, CharSet CharSet.Auto, SetLastError true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName); // 原生读取API [DllImport(kernel32.dll, CharSet CharSet.Auto)] private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName); /// summary写入ini键值/summary public static void Write(string section, string key, string value) { WritePrivateProfileString(section, key, value, filePath); } /// summary读取ini指定键值/summary public static string Read(string section, string key) { StringBuilder sb new StringBuilder(255); GetPrivateProfileString(section, key, , sb, 255, filePath); return sb.ToString(); } } }3. 完整底层工具 IniAPI.csTool 公共类库核心能力获取全部 Section 节点名获取单个节点下全部 keyvalue 键值对读取字符串 /int/double 类型配置删除 Key、删除整个节点、清空节点内容批量写入节点多条数据核心 API 原理通过DllImport引入kernel32.dll非托管 Windows 原生 INI 操作函数使用Marshal封送内存缓冲区读取多段\0分隔文本。4. 窗体调用示例// 写入 INITool.Write(Address, serve, textBox1.Text); INITool.Write(Address, port, textBox2.Text); // 读取 textBox1.Text INITool.Read(Address, serve); // 获取节点下所有键值数组 string[] arr IniAPI.INIGetAllItems(filePath, Address); // 删除键 IniAPI.INIDeleteKey(filePath,Address,port); // 删除整个节点 IniAPI.INIDeleteSection(filePath,相机);INI 文件格式规范[Address] serve127.0.0.1 port8080 [相机] 曝光300[Section]配置节点节keyvalue键值对无空格、区分大小写API 可自动兼容三、CSV 逗号分隔表格文件案例 3适用场景轻量表格存储可用 Excel 直接打开纯文本无依赖适合导出简单列表数据。CSVAPI 完整工具类using System; using System.IO; using System.Text; namespace _3csv数据格式 { public class CSVAPI { // 追加一行数据自动创建目录、自动写入表头 public static void SaveData(string name, string age, string sex) { string dir Directory.GetCurrentDirectory() \data; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string file dir \1.csv; // 文件不存在创建并写入表头 if (!File.Exists(file)) { using (StreamWriter sw new StreamWriter(file, false, Encoding.Default)) { sw.WriteLine(姓名,年龄,性别); } } // 追加数据行 using (StreamWriter sw new StreamWriter(file, true, Encoding.Default)) { sw.WriteLine(${name},{age},{sex}); } } // 读取完整CSV文本 public static string ReadData() { string dir Directory.GetCurrentDirectory() \data; if (!Directory.Exists(dir)) Directory.CreateDirectory(dir); string file dir \1.csv; using (StreamReader sr new StreamReader(file, Encoding.Default)) { return sr.ReadToEnd(); } } } }窗体读取解析逻辑private void button2_Click(object sender, EventArgs e) { string allText CSVAPI.ReadData(); // 按换行分割所有行 string[] lines allText.Split(\n); // 跳过表头、跳过末尾空行 for (int i 1; i lines.Length - 1; i) { string[] rowData lines[i].Split(,); string name rowData[0]; string age rowData[1]; string sex rowData[2]; } }CSV 格式规则第一行为表头逗号分隔字段每行一条数据字段逗号隔开缺陷字段内容包含逗号 / 换行时会解析错乱复杂表格推荐 JSON示例文件内容姓名,年龄,性别 梅西,20,男 张三,25,女四、项目 Settings 用户配置案例 4特点VS 可视化配置无需手动写 xml分Application程序级只读、User用户级可运行修改保存自动序列化支持 string、int、bool、Color 等类型存储路径C:\Users\ 当前用户 \AppData\Local\ 项目名使用步骤项目右键 → 属性 → 设置 → 添加 name/age/sex 字段代码读写// 写入修改 Settings set Settings.Default; set.name 李四; set.age 40; set.sex true; set.Save(); // 持久化保存到本地用户配置文件 // 读取 string userName Settings.Default.name;底层生成 App.config 配置userSettings _4setting读写.Properties.Settings setting namename serializeAsString value张三/value /setting setting nameage serializeAsString value20/value /setting /_4setting读写.Properties.Settings /userSettings五、try-catch 异常捕获案例 5核心作用捕获程序运行错误避免程序直接崩溃友好提示错误信息。分层捕获规则优先级从上到下特定细分异常精准捕获FormatException字符串转数字格式错误OverflowException数值超出类型范围IndexOutOfRangeException数组索引越界NullReferenceException空对象调用属性 / 方法DivideByZeroException除以 0ArgumentException传入非法参数Exception所有异常基类兜底捕获必须放最后标准模板try { // 可能报错的业务代码 int num int.Parse(textBox1.Text); int[] arr new int[3]; int val arr[num]; } catch (FormatException ex) { MessageBox.Show(输入不是合法数字 ex.Message); } catch (IndexOutOfRangeException ex) { MessageBox.Show(数组索引超出范围 ex.Message); } catch (Exception ex) { // 未知异常兜底 MessageBox.Show(程序异常 ex.Message); // throw ex; // 抛出异常终止程序 } finally { // 无论是否报错一定会执行释放文件、关闭流 }关键字说明try监控异常代码块catch捕获对应类型异常处理错误finally资源释放专用文件流、数据库连接throw主动抛出异常中断程序运行六、五种本地存储方案对比方案优点缺点使用场景JSON结构清晰、支持复杂对象、易序列化原生无 API需 Newtonsoft列表、对象集合、表格数据INI轻量、读写速度快、配置专用不支持嵌套对象只存简单键值软件参数、串口 / 相机 / 数据库配置CSVExcel 可打开、纯文本、无第三方依赖复杂文本解析错乱无嵌套简单报表导出、一维列表SettingsVS 可视化配置、开箱即用、类型安全存储路径固定不适合多套配置用户界面布局、简单全局参数XML原生.NET 支持层级结构文件体积大、语法繁琐老旧项目配置现已被 JSON 替代七、总结简单键值配置优先使用 INI、Settings开发效率最高列表、复杂对象展示存储优先 JSONDataGridView需要 Excel 打开导出数据选择 CSV所有文件 IO、类型转换、数组操作代码必须包裹try-catch防止程序崩溃INI 底层依赖 Windows 非托管 kernel32 API跨平台程序不建议使用资源操作FileStream、StreamReader统一使用using自动释放资源避免文件占用。