如何将文本文件中指定内容加载到对应TextBox控件中
完善WinForms加载键值对文本文件的实现
我来帮你把这个加载文件的逻辑补全,刚好匹配你这种Key = Value格式的测试数据文件。下面是完整的实现代码和细节说明:
完整的加载按钮事件代码
private void btn_LoadFile_Click(object sender, EventArgs e) { OpenFileDialog fdlg = new OpenFileDialog(); // 设置文件筛选器,只显示文本文件,方便用户选择 fdlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; fdlg.Title = "选择测试数据文件"; // 默认打开程序运行目录,提升操作便捷性 fdlg.InitialDirectory = Application.StartupPath; if (fdlg.ShowDialog() == DialogResult.OK) { try { // 一次性读取文件所有行,适合小体积的测试数据文件 string[] lines = File.ReadAllLines(fdlg.FileName); // 逐行解析键值对 foreach (string line in lines) { // 跳过空行或格式不规范的行,避免解析出错 if (string.IsNullOrWhiteSpace(line) || !line.Contains("=")) continue; // 只分割第一个"=",防止值里包含"="的情况(虽然你的场景大概率不会,但做兼容更稳妥) string[] parts = line.Split(new[] { '=' }, 2); string key = parts[0].Trim(); string value = parts[1].Trim(); // 根据键匹配对应的TextBox赋值,记得替换成你实际的控件名称 switch (key) { case "Serial Number": txtSerialNumber.Text = value; break; case "Type Number": txtTypeNumber.Text = value; break; case "Test Engineer": txtTestEngineer.Text = value; break; case "Date": txtDate.Text = value; break; case "Time": txtTime.Text = value; break; case "Test1": txtTest1.Text = value; break; case "Test2": txtTest2.Text = value; break; // 这里继续添加Test3到Test18对应的TextBox分支 case "Test18": txtTest18.Text = value; break; default: // 遇到未知键可以选择忽略,或者弹出提示告知用户 break; } } MessageBox.Show("文件加载成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { // 捕获并提示所有可能的错误,比如文件被占用、格式异常等 MessageBox.Show($"加载文件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
关键细节说明
- 命名空间依赖:记得在代码文件顶部添加
using System.IO;,否则File类、文件对话框相关API会报错。 - 大文件兼容:如果你的测试数据文件体积很大,建议替换成
StreamReader逐行读取,避免一次性加载过多内容占用内存。 - 控件名称匹配:代码里的
txtSerialNumber、txtTest1等是示例控件名,一定要替换成你项目中实际的TextBox名称,不然会出现编译错误。 - 格式容错:代码里跳过了空行和不含
=的行,能避免因文件格式不规范导致的崩溃。
可选补充:保存按钮代码
如果需要实现对应的保存功能,这里给你一个参考实现:
private void btn_SaveFile_Click(object sender, EventArgs e) { SaveFileDialog sdlg = new SaveFileDialog(); sdlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; sdlg.Title = "保存测试数据文件"; sdlg.InitialDirectory = Application.StartupPath; // 自动生成带时间戳的文件名,避免覆盖旧文件 sdlg.FileName = $"TestData_{DateTime.Now:yyyyMMddHHmmss}.txt"; if (sdlg.ShowDialog() == DialogResult.OK) { try { // 构建要写入的内容列表 List<string> content = new List<string> { $"Serial Number = {txtSerialNumber.Text}", $"Type Number = {txtTypeNumber.Text}", $"Test Engineer = {txtTestEngineer.Text}", $"Date = {txtDate.Text}", $"Time = {txtTime.Text}", $"Test1 = {txtTest1.Text}", $"Test2 = {txtTest2.Text}", // 继续添加Test3到Test18的内容 $"Test18 = {txtTest18.Text}" }; // 写入文件 File.WriteAllLines(sdlg.FileName, content); MessageBox.Show("文件保存成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show($"保存文件失败:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
内容的提问来源于stack exchange,提问作者User0804
相关产品推荐
相关产品推荐

