文件操作综合实战#
来源:
D:\study\C#1\WinForm\stu0811\text文件、stu0811\保存text文件、stu0812\0812作业\SaveClass
综合运用前面几篇的知识,实现「保存数据 → 查询数据 → 异常处理」的完整文件操作。
1. 实战一:保存文本 + 图片(stu0811/text文件)#
用户录入信息(姓名、年龄、性别、备注),保存为文本文件,同时保存一张图片,再支持按姓名查询。
1.1 保存(文本 + 图片)#
private void button1_Click(object sender, EventArgs e)
{
// 1. 组装一行数据(逗号分隔)
string file = $"{Name1.Text},{Age1.Text},{Sex1.Text},{Min1.Text}";
// 2. 创建目录(不存在才创建)
string path = Directory.GetCurrentDirectory() + @"/filetext";
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// 3. 追加写入文本
using (FileStream fs = new FileStream(path + "\\textTest.txt", FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(file.Trim());
}
// 4. 保存图片(PictureBox 里当前显示的图片)
if (!Directory.Exists(Directory.GetCurrentDirectory() + @"imge"))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + @"imge");
}
pictureBox1.Image.Save($@"./imge/{Name1.Text}a.png", System.Drawing.Imaging.ImageFormat.Png);
MessageBox.Show("保存成功!");
}
1.2 按姓名查询(逐行匹配 + 回显)#
private void button4_Click(object sender, EventArgs e)
{
string path = Directory.GetCurrentDirectory() + @"/filetext";
string tfile = path + "\\textTest.txt";
using (FileStream fs = new FileStream(tfile, FileMode.Open, FileAccess.Read))
using (StreamReader sr = new StreamReader(fs))
{
string line;
while ((line = sr.ReadLine()) != null)
{
// 按逗号拆分,第一列是姓名
if (line.Split(',')[0] == textBox5.Text)
{
MessageBox.Show("找到数据");
Name1.Text = line.Split(',')[0]; // 回显到界面
Age1.Text = line.Split(',')[1];
Sex1.Text = line.Split(',')[2];
Min1.Text = line.Split(',')[3];
// 同步加载对应的图片
if (File.Exists($@"./imge/{Name1.Text}a.png"))
{
pictureBox1.ImageLocation = $@"./imge/{Name1.Text}a.png";
path1.Text = $@"./imge/{Name1.Text}a.png";
}
else
{
MessageBox.Show($"{Name1.Text} 不存在图片");
}
return; // 找到后退出
}
}
}
MessageBox.Show("未找到数据");
}
💡 这是一个完整的「数据存储 + 查询回显」模式:逗号分隔文本是简易数据库,按行读取、按列匹配。
2. 实战二:封装保存类(stu0812/0812作业/SaveClass)#
把保存逻辑封装成工具类,支持保存文本、保存 CSV、写日志,带异常处理。
2.1 保存文本(自动创建目录)#
internal class SaveClass
{
// 保存文本:自动创建文件夹
public void SaveText(string str)
{
// 文件夹路径
string textFile = Directory.GetCurrentDirectory() + "\\Text文件夹";
if (!Directory.Exists(textFile))
{
Directory.CreateDirectory(textFile);
}
// 文件路径 + 追加
string file = textFile + "\\文本.txt";
File.AppendAllText(file, str);
}
}
2.2 保存 CSV(带异常处理和返回值)#
// 保存 CSV 和 TXT,返回是否成功
public bool Save(string path, string a, string b, string c, string d, string e)
{
bool flag;
try
{
// 目录不存在则创建
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// 保存 CSV(Append 追加,UTF-8 编码)
using (FileStream fs = new FileStream(path + "\\Data.csv", FileMode.Append, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
{
StringBuilder sb = new StringBuilder();
sb.Append(a).Append(",").Append(b).Append(",").Append(c).Append(",").Append(d).Append(",").Append(e);
sw.WriteLine(sb.ToString().Trim());
}
// 同时保存 TXT
var str = $"{a},{b},{c},{d},{int.Parse(e)}";
File.AppendAllText(path + "//Text.txt", $"{str}\r\n".TrimStart());
flag = true;
}
catch (Exception ex)
{
SaveLog(ex, path); // 出错写日志
flag = false;
}
return flag;
}
2.3 异常日志#
// 把异常写入日志文件
public void SaveLog(Exception exception, string path)
{
File.AppendAllText(path + "\\log.txt",
$"{DateTime.Now.ToString()}----{exception.ToString()}\r\n\n".TrimStart(),
Encoding.UTF8);
}
💡 封装工具类的意义: - 保存逻辑只写一次,到处调用 -
try...catch防止程序崩溃 - 出错自动记录日志,方便排查
3. 实战三:ListView 数据保存 CSV(stu0812/ListView控件)#
// 把 ListView 中的数据保存为 CSV 文件
public void Writesave()
{
using (FileStream fs = new FileStream(@"./Data.csv", FileMode.Create, FileAccess.Write))
using (StreamWriter sw = new StreamWriter(fs))
{
StringBuilder sb = new StringBuilder();
foreach (ListViewItem item in listView1.Items)
{
// 每行 = 各列拼接(逗号分隔)
// sb.AppendLine($"{item.Text},{item.SubItems[1].Text},...");
}
}
MessageBox.Show("保存成功");
}
💡 CSV(Comma-Separated Values)就是用逗号分隔的文本表格,Excel 可以直接打开,是数据交换的常用格式。
4. 模式总结#
保存:组装字符串(逗号/竖线分隔)→ 确保目录存在 → 追加写入(FileMode.Append)
查询:逐行读取 → Split 拆分 → 按字段匹配 → 回显 / 处理
健壮性:try...catch + 日志文件 + bool 返回值
相关笔记:
04-文本流读写、01-File与Directory、02-Path路径操作。
相关笔记#
- File 与 Directory — 文件操作
- 文本流读写 StreamReader 与 StreamWriter — 文本流
- WinForms 图书管理系统 — 图书管理系统