C# List如何生成Txt文档且读取Txt文档封装List(list,txt,开发技术)

时间:2024-05-03 12:34:53 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :

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

一、简单设计界面

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

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

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

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

二、方法函数讲解

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

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

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

三、效果展示

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

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

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

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

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

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

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

四、代码逻辑

界面代码:

usingDictionaryToTxtFile;usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Windows.Forms;namespaceIC00520{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();}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”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

本文:C# List如何生成Txt文档且读取Txt文档封装List的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:vue如何实现路由按需加载下一篇:

7 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18