C#?List如何生成Txt文档且读取Txt文档封装List


这篇文章主要介绍“C#List如何生成Txt文档且读取Txt文档封装List”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“C#List如何生成Txt文档且读取Txt文档封装List”文章能帮助大家解决问题。

一、简单设计界面

做一个简单的界面,两个触发按钮,对我们写的代码,进行控制(可以直接跳到后面看代码)

窗体触发函数,双击按钮得到的触发函数,编写触发函数的触发条件和逻辑

二、方法函数讲解

总共两个函数,一个读,一个写,分别对应不同的代码,代码逻辑很简单,可以直接拷贝使用,也可以根据自己的需求做更改。代码在文末

三、效果展示

博主只是模拟一部风数据,将数据放进list中,再设置好你需要放置文件的位置,你可以设置任意位置,调用函数将list和文件保存路径作为参数传过去就可以了

生成之后的文件如上图所示,Txt文件中有100个数值。接下来我们把这个txt文件中的数据再读出来,封装进List中。

四、代码逻辑

界面代码:

usingDictionaryToTxtFile;usingSystem;usingSystem.Collections.Generic;usingSystemponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceIC00520{publicpartialclassForm1:Form{publicForm1(){Initializponent();}publicstaticDaodao=newDao();//调用方法的声明privatevoidbutton1_Click(objectsender,EventArgse){OpenFileDialogopenFile=newOpenFileDialog();//定义打开文件类openFile.Filter="Txt文件(*.Txt)|*.txt|所有文件|*.*";if(openFile.ShowDialog()!=DialogResult.OK)//打开文件是否点击了取消return;stringpath=openFile.FileName;//获得你打开文件的名称,路径List<int>datalist=dao.WriteData(path);//调用方法foreach(intiindatalist)//遍历展示数据{richTextBox1.Text+=i.ToString()+"\r\n";}}privatevoidbutton2_Click(objectsender,EventArgse){List<int>list=newList<int>();for(inti=0;i<100;i++)//生成100个虚拟数据测试{list.Add(i);}dao.SaveData(list,"C:\Users\ASUS\source\repos\IC00520\IC00520\");//将数据和文件路径作为实参}}}

方法类代码:

usingSystem;usingSystem.Collections.Generic;usingSystem.IO;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceDictionaryToTxtFile{publicclassDao{publicstringSaveData(List<int>info,stringpath){try{stringdataName="";//数据下发文件名stringData="";foreach(varitemininfo)//遍历List数据将数据保存在Data中{Data+=item+"\r\n";}dataName="IC00"+DateTime.Now.ToString("yyyy_MM_ddHH_mm_ss")+".txt";//以日期创建文件名path+=dataName;File.AppendAllText(path,Data);//直接追加,如果没有这个文件会自动添加return"OK";}catch(Exceptionex){returnex.Message.ToString();}}publicList<int>WriteData(stringfilepath){try{List<int>info=newList<int>();string[]lines=File.ReadAllLines(filepath);//读取文件中的所有行并将所有行放进string数组中for(inti=0;i<lines.Length;i++){intvalue=int.Parse(lines[i]);//遍历赋值,返回list的值info.Add(value);}returninfo;}catch(Exceptionex){returnnull;}}}}

关于“C#List如何生成Txt文档且读取Txt文档封装List”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注主机评测网行业资讯频道,小编每天都会为大家更新不同的知识点。


上一篇:Spring?Security的过滤器链机制是什么

下一篇:python3如何实现倒计时效果


Copyright © 2002-2019 测速网 www.inhv.cn 皖ICP备2023010105号
测速城市 测速地区 测速街道 网速测试城市 网速测试地区 网速测试街道
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!

热门搜索 城市网站建设 地区网站制作 街道网页设计 大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器