C#对txt文件的读写操作
2022/7/15 1:20:07
本文主要是介绍C#对txt文件的读写操作,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/// <summary> /// 向文本里面写入配置信息 /// </summary> public void WriteConfigToTxt(int times, int days, string delPath) { try { string user = Environment.GetFolderPath(Environment.SpecialFolder.Templates); string configPath = user + "\\ConfigFile"; //string logPath = "c:\\LogFile"; //判断该路径下文件夹是否存在,不存在的情况下新建文件夹 if (!Directory.Exists(configPath)) { Directory.CreateDirectory(configPath); } //指定日志文件的目录 string fname = configPath + "\\ConfigFile.txt"; //先将文本清空 System.IO.File.WriteAllText(fname, string.Empty); //定义文件信息对象 FileInfo finfo = new FileInfo(fname); if (!finfo.Exists) { FileStream fs; fs = File.Create(fname); fs.Close(); finfo = new FileInfo(fname); } //创建只写文件流 using (FileStream fs = finfo.OpenWrite()) { //根据上面创建的文件流创建写数据流 StreamWriter w = new StreamWriter(fs); //设置写数据流的起始位置为文件流的末尾 w.BaseStream.Seek(0, SeekOrigin.End); //写入内容 w.Write(times.ToString() + "\n" + days + "\n" + delPath + "\n\r"); //清空缓冲区内容,并把缓冲区内容写入基础流 w.Flush(); //关闭写数据流 w.Close(); } } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } } /// <summary> /// 读取txt文件,并返回文件中的内容 /// </summary> public string ReadTxTContent() { try { string user = Environment.GetFolderPath(Environment.SpecialFolder.Templates); string contentPath = user + "\\ConfigFile"; if (Directory.Exists(contentPath)) { string strCon = string.Empty; // 创建一个 StreamReader 的实例来读取文件 // using 语句也能关闭 StreamReader contentPath = contentPath + "\\ConfigFile.txt"; using (StreamReader sr = new StreamReader(contentPath)) { string line; // 从文件读取并显示行,直到文件的末尾 while ((line = sr.ReadLine()) != null) { strCon += line + " "; } } return strCon; } return null; } catch (Exception e) { Console.WriteLine(e.Message); return null; } }
这篇关于C#对txt文件的读写操作的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-03-01沐雪多租宝商城源码从.NetCore3.1升级到.Net6的步骤
- 2024-05-08首个适配Visual Studio平台的国产智能编程助手CodeGeeX正式上线!C#程序员必备效率神器!
- 2024-03-30C#设计模式之十六迭代器模式(Iterator Pattern)【行为型】
- 2024-03-29c# datetime tryparse
- 2024-02-21list find index c#
- 2024-01-24convert toint32 c#
- 2024-01-24Advanced .Net Debugging 1:你必须知道的调试工具
- 2024-01-24.NET集成IdGenerator生成分布式全局唯一ID
- 2024-01-23用CI/CD工具Vela部署Elasticsearch + C# 如何使用
- 2024-01-23.NET开源的简单、快速、强大的前后端分离后台权限管理系统