C# 文件操作

news/2024/9/22 16:29:41/文章来源:https://www.cnblogs.com/zeussbook/p/18332682

本篇主要记录C#操作文件

相对路径在项目文件...\bin\Debug 目录下

一、写入读取文件

写入
        /// <summary>/// initial 文件写入/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button1_Click(object sender, EventArgs e){//1.创建一个键值对Dictionary<String, Dictionary<string, string>> data = new Dictionary<string, Dictionary<string, string>>();//2.添加数据源data.Add("设备套接字", new Dictionary<string, string>(){{"ip","192.168.21.11" },{"端口","502" }});//3.写入到本地using (StreamWriter streamWriter = new StreamWriter(path,true)){//4.循环写入foreach (string item in data.Keys){//4.1写入键streamWriter.WriteLine($"[{item}]");//5.写入值foreach (string item2 in data[item].Keys){streamWriter.WriteLine($"{item2}={data[item][item2]}");}}}}
      
读取
        /// <summary>/// initial 文件读取/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button2_Click(object sender, EventArgs e){Dictionary<String, Dictionary<string, string>> saveData = new Dictionary<string, Dictionary<string, string>>();string key = null;//配置io流using (StreamReader reader = new StreamReader(path,true)){while (!reader.EndOfStream){//读取string data = reader.ReadLine();//判断是否键if (data.StartsWith("[") && data.EndsWith("]")){key = data.Substring(1, data.Length - 2);saveData.Add(key,new Dictionary<string, string>());}//判断是否是值else if (!string.IsNullOrEmpty(data) && !data.EndsWith(";")){int index = data.IndexOf("=");if (index > 0){//获取值saveData[key].Add(data.Substring(0,index), data.Substring(index+1));}}}}}

二、文件的基本操作

目录操作
        /// <summary>/// 创建目录/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button1_Click(object sender, System.EventArgs e){//###一.创建文件夹两种路径方式//1.相对路径地址,项目输出路径,在../bin/Debug目录下Directory.CreateDirectory("log");//在创建的目录中创建子目录Directory.CreateDirectory("log/zhangsan");//2.绝对路径地址,加磁盘符//Directory.CreateDirectory("D:\\c#\\source\\test");// ###2.判断指定路径下是否有该目录if (Directory.Exists("log")){MessageBox.Show("存在");}}/// <summary>/// 删除目录/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button2_Click(object sender, System.EventArgs e){//删除目录,删除的目录必须为空,见构造方法Directory.Delete("log/zhangsan",true);MessageBox.Show(Directory.Exists("log")?"删除成功":"删除失败");}/// <summary>/// 查询子文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button3_Click(object sender, System.EventArgs e){//查询目录下的文件,不是文件夹,文件是带后缀名的,例如:111.txtstring[] files = Directory.GetFiles("log");foreach (var item in files){MessageBox.Show(item);}}

 

文件流
 // FileStream: 文件流
Encoding encoding = Encoding.UTF8;//二进制转换格式/// <summary>/// 写入文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button4_Click(object sender, System.EventArgs e){//第一步:配置文件操作对象string path = "opreationLog.txt";FileMode fileMode = FileMode.Append;FileAccess fileAccess = FileAccess.Write;//初始化IO流对象FileStream fileStream = new FileStream(path, fileMode, fileAccess);//第二步:写入//TODO: 注意这里要加入 \r 才能识别保存换行byte[] data = encoding.GetBytes($"{textBox1.Text}\r\n");fileStream.Write(data,0,data.Length);//关闭IO流
            fileStream.Close();}/// <summary>/// 读取文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button5_Click(object sender, System.EventArgs e){//第一步:配置文件操作对象string path = "opreationLog.txt";FileMode fileMode = FileMode.Open;FileAccess fileAccess = FileAccess.Read;//初始化IO流对象FileStream fileStream = new FileStream(path, fileMode, fileAccess);byte[] readBytes = new byte[1024];fileStream.Read(readBytes, 0, 1024);textBox2.Text = encoding.GetString(readBytes);//关闭IO流
            fileStream.Close();}

 

序列化
        /// <summary>/// 序列化导出/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button6_Click(object sender, System.EventArgs e){//第一步:配置文件操作对象string path = "save_person.txt";FileMode fileMode = FileMode.Create;FileAccess fileAccess = FileAccess.Write;// 第二步:配置io流对象//using自动管理关闭文件流using (FileStream fileStream = new FileStream(path, fileMode, fileAccess)){//创建序列化对象BinaryFormatter binary = new BinaryFormatter();//获取表格中的数据List<Person> persons = new List<Person>();Person person;for (int i = 0; i < dataGridView1.Rows.Count-1; i++){person = new Person();person.Id = Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value); person.Name = dataGridView1.Rows[i].Cells[1].Value.ToString(); person.Age = Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value); persons.Add(person);}//开始序列化
                binary.Serialize(fileStream,persons);}}/// <summary>/// 序列化导入/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button7_Click(object sender, EventArgs e){//第一步:配置文件操作对象string path = "save_person.txt";FileMode fileMode = FileMode.Open;FileAccess fileAccess = FileAccess.Read;// 第二步:配置io流对象//using自动管理关闭文件流using (FileStream fileStream = new FileStream(path, fileMode, fileAccess)){//创建序列化对象BinaryFormatter binary = new BinaryFormatter();//反序列化Object obj = binary.Deserialize(fileStream);//转换成集合List<Person> people = (List<Person>)obj;//清理表格上的数据
                dataGridView1.Rows.Clear();//循环写入foreach (var item in people){dataGridView1.Rows.Add(item.Id, item.Name, item.Age);}}}}[Serializable]class Person{}

 

三、CSV文件

        /// <summary>/// 导入CSV/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button2_Click(object sender, EventArgs e){//第一步:配置IO流操作对象using (StreamReader streamReader = new StreamReader("产品数据.csv")){int index = 0;while(!streamReader.EndOfStream){string data = streamReader.ReadLine();string[] str = data.Split(',');//不插入表头if (index > 0){dataGridView1.Rows.Add(str);}index++;}}}/// <summary>/// 导出CSV/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button1_Click(object sender, EventArgs e){//第一步:配置文件流操作对象using(StreamWriter streamWrite = new StreamWriter("产品数据.csv",false)){//加入表头streamWrite.WriteLine($"{dataGridView1.Columns[0].HeaderText},{dataGridView1.Columns[1].HeaderText},{dataGridView1.Columns[2].HeaderText}");//第二步:循环写入for (int i = 0; i < dataGridView1.Rows.Count -1; i++){streamWrite.WriteLine($"{dataGridView1.Rows[i].Cells[0].Value},{dataGridView1.Rows[i].Cells[1].Value},{dataGridView1.Rows[i].Cells[2].Value}");}}}

 

四、Excel

       /// <summary>/// 导出excel文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button4_Click(object sender, EventArgs e){//第一步:配置Excel文件操作对象using (XLWorkbook xl = new XLWorkbook()){//第二步:创建工作页IXLWorksheet sheet = xl.AddWorksheet("产品数据页1");//第三步:循环添加数据//写入表头for (int i = 0; i < dataGridView1.Columns.Count; i++){//注意Cell 必须从1开始,否则报错sheet.Cell(1, i + 1).Value = dataGridView1.Columns[i].HeaderText;}//写入表格数据for (int i = 0; i < dataGridView2.Rows.Count-1; i++){//第四步:获取第i行列的值for (int j = 0; j < dataGridView2.Rows[i].Cells.Count; j++){//第五步:写入数据sheet.Cell(i+2,j+1).Value = dataGridView2.Rows[i].Cells[j].Value.ToString();}}//第六步:保存到本地xl.SaveAs("数据.xlsx");}}/// <summary>/// 导入Excel文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void Button3_Click(object sender, EventArgs e){//第一步:配置Excel文件操作对象using (XLWorkbook xl = new XLWorkbook("数据.xlsx")){//第二步:获取第一个sheet页IXLWorksheet workbook = xl.Worksheet(1);//第三步:获取sheet页中数据
                IXLRow row;List<string> list;// 从2开始不要表头for (int i = 2; i <= workbook.Rows().Count(); i++){row = workbook.Row(i);list = new List<string>();for (int j = 1; j <= row.Cells().Count(); j++){string data = workbook.Cell(i, j).Value.ToString();list.Add(data);}dataGridView2.Rows.Add(list);}}}

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/774109.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python 环境配置(二)安装jupyter、matplotlib、numpy库

Python 环境配置(二)安装jupyter、matplotlib、numpy库 一、numpypip install numpy二、matplotlibpip install matplotlib 三、jupyter 1、anaconda自带Jupyter 2、pycharm 插件只有 Pycharm 的 Professional 版才支持 Jupyter Notebook,请注意版本3、新建文件#%%import nu…

Meta SAM 2:实时分割图片和视频中对象;Apple Intelligence 首个开发者测试版发布丨 RTE 开发者日报

开发者朋友们大家好:这里是 「RTE 开发者日报」 ,每天和大家一起看新闻、聊八卦。我们的社区编辑团队会整理分享 RTE(Real-Time Engagement) 领域内「有话题的新闻」、「有态度的观点」、「有意思的数据」、「有思考的文章」、「有看点的会议」,但内容仅代表编辑的个人观点…

Python 环境配置(一)Python、Anaconda、Pycharm的安装

Python 环境配置(一)Python、Anaconda、Pycharm的安装本人之前已安装一次,此次为卸载之后的重新安装。。。一、Python 1、下载 下载官网: 下载链接:Download Python | Python.org勾选 添加到路径 (环境变量)next如图所示之后点close关闭2、验证 win+R cmd: python退出 …

C++ - VS2019配置pthread线程库

1. 说明 在VS里用MS编译器不能直接调用pthread库,需要先自行下载该库:http://sourceware.org/pub/pthreads-win32/pthreads-w32-2-9-1-release.zip 解压后用得到的只有Pre-built.2文件夹下的文件。2. 配置 如下图分别配置三大项:包含目录-->...pthreads-w32-2-9-1-releas…

Windows安全策略

Windows 安全策略是系统管理的一部分,用于设置和管理计算机或网络的安全配置。保护系统免受未经授权的访问和其他安全威胁。常见 Windows 安全策略分类: 1. 账户策略 (Account Policies) 账户策略管理用户账户的行为和属性,主要包括: • 密码策略: • 密码历史记录:限制用…

lca总结+树上差分

lca lca简称最近公共祖先——简介在此,不过多赘述 这里主要写的是倍增算法,oi-wiki上用的是vector,由于本人不会,只会用链表,所以这里就放链表的代码了例题加一个数组按倍增数组的方式存距离即可题解——点击查看代码 #include<bits/stdc++.h> #define int long lon…

基于OM6626/NRF528210系列的ESL电子价签应用

在竞争激烈的零售行业,效率和顾客体验至关重要。传统的纸质价签在更新频率、准确性和管理成本上存在诸多不足。而电子价签(ESL,Electronic Shelf Label)作为一种智能化解决方案,正在逐渐取代传统价签,帮助零售商提高运营效率和顾客满意度。01电子价签的优势 电子价签通过…

模拟退火

模拟退火 必须要单独开一个专题来讲模拟退火了。 看到身边很多同学写的模退都是不标准的,步长没有随温度的降低而减小,只能叫随机爬山。 系统的学习模退是跟着 Acwing 的 yxc,他写的模退给人一看就有一种豁然开朗,神清气爽的感觉,让你惊叹天下竟然还有如此精妙的算法。 是…

成为Apache SeaTunnel贡献者的N种方式

如何参与开源贡献参与开源贡献的常见方法有多种:1)参与解答 在社区中, 帮助使用过程中遇到困难的人,帮他们解释框架的用法也算是一种贡献。 2)文档贡献 帮助框架来完善文档,比如说将英文文档翻译为中文,纠正文档里面的错误单词,这 是很多人参与开源贡献的第一步。 3)代…

构建个性化财务数据看板,免费可视化工具来助力

财务月度数据,作为企业经营的晴雨表,其重要性不言而喻。然而,面对海量、复杂的数据,如何快速提炼关键信息,形成直观易懂的洞察报告,成为了众多企业面临的挑战。随着技术的不断进步,可视化工具正逐步成为财务数据分析领域的得力助手,帮助企业轻松构建财务月度数据看板,…

企业级Scrum敏捷开发培训:推动团队高效运作

“企业级Scrum敏捷开发培训:推动团队高效运作”​ 在当今快速变化的商业环境中,企业必须不断创新和快速响应市场需求,以保持竞争优势。Scrum敏捷开发方法作为一种高效的项目管理框架,已被全球众多企业采用,用于提高团队协作和交付速度。为了帮助企业更好地理解和应用Scrum…