当前位置: 首页 > news >正文

C#文件操作(创建、读取、修改)

判断文件是否存在  不存在则创建默认文件 并写入默认值

        /// <summary>/// 判断文件是否存在  不存在则创建默认文件 并写入默认值/// </summary>public void IsConfigFileExist(){try{// 获取应用程序的当前工作目录。string fileName = System.IO.Directory.GetCurrentDirectory();string path = fileName + "\\Config";if (!Directory.Exists(path))      //此文件夹是否存在{Directory.CreateDirectory(path); //创建文件夹}//创建IP文件夹string path1 = path + "\\IPAdderss.ini";System.IO.FileInfo fi = new System.IO.FileInfo(path1);if (!File.Exists(path1))       //判断IPAdderss.txt是否存在{//不存在文件,则创建IPAdderss.txt文件FileStream fs = new FileStream(path1, FileMode.Create, FileAccess.Write);fs.Close();//打开文件StreamWriter sw = new StreamWriter(path1);//定义一个键值对集合Dictionary<string, string> dictionary = new Dictionary<string, string>();//添加键值对数据,键必须唯一,值可重复dictionary.Add("IP", "192.168.0.100");//通过键值对遍历集合foreach (KeyValuePair<string, string> kv in dictionary){//向文件中写入参数sw.WriteLine(kv.Key + "=" + kv.Value);}//向文件中写入参数//关闭文件sw.Close();}//创建用户文件夹,存储用户名和密码path1 = path + "\\User.ini";fi = new System.IO.FileInfo(path1);if (!File.Exists(path1))       //判断IPAdderss.txt是否存在{//不存在文件,则创建IPAdderss.txt文件FileStream fs = new FileStream(path1, FileMode.Create, FileAccess.Write);fs.Close();//Hashtable ht = new Hashtable();//ht.Add("操作员", "123456");//ht.Add("管理员", "admin");//var mm = ht["IP"];//打开文件StreamWriter sw = new StreamWriter(path1);//定义一个键值对集合Dictionary<string, string> dictionary = new Dictionary<string, string>();//添加键值对数据,键必须唯一,值可重复dictionary.Add("操作员", "123456");dictionary.Add("管理员", "admin");//通过键值对遍历集合foreach (KeyValuePair<string, string> kv in dictionary){//向文件中写入参数sw.WriteLine(kv.Key + "=" + kv.Value);}//向文件中写入参数//关闭文件sw.Close();}}catch (Exception ex){MessageBox.Show("异常:" + ex.Message);}}

执行效果:创建文件并写入默认值(以键值对形式)

通过键和文件名读取文件中的值

 /// <summary>/// 读取文件/// </summary>/// <param name="keyName">键名</param>/// <param name="FileName">文件名</param>/// <returns></returns>public string ReadConfigFile(string keyName, string FileName){// 获取应用程序的当前工作目录。string fileName = System.IO.Directory.GetCurrentDirectory();string path = fileName + "\\Config";string filePath = path + "\\" + FileName;string returnValue = "";if (!Directory.Exists(path))      //此文件夹是否存在{IsConfigFileExist();}Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();using (StreamReader reader = new StreamReader(filePath)){string line;while ((line = reader.ReadLine()) != null){string[] parts = line.Split('=');if (parts.Length == 2){keyValuePairs[parts[0].Trim()] = parts[1].Trim();}}}foreach (var kvp in keyValuePairs){//Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}");if (kvp.Key == keyName){return kvp.Value;}}return returnValue;}

执行效果:读取键名为R1的值

通过键修改文件中的值

      /// <summary>/// 修改文件/// </summary>/// <param name="modifyKeyName">键名</param>/// <param name="modifyKeyValue">键值</param>/// <param name="modifyFileName">文件名</param>/// <returns></returns>public bool UpdateConfigFile(string modifyKeyName, string modifyKeyValue, string modifyFileName){try{// 获取应用程序的当前工作目录。string fileName = System.IO.Directory.GetCurrentDirectory();string path = fileName + "\\Config\\" + modifyFileName;string keyToUpdate = modifyKeyName;string newValue = modifyKeyValue;// 读取文件内容到字符串数组string[] lines = File.ReadAllLines(path);string updatedContent = "";bool keyFound = false;foreach (var line in lines){if (line.StartsWith(keyToUpdate + "=")){// 找到键,修改值updatedContent += $"{keyToUpdate}={newValue}\n";keyFound = true;}else{// 未找到键,直接添加原行updatedContent += line + "\n";}}if (!keyFound){// 如果键不存在,添加新的键值对updatedContent += $"{keyToUpdate}={newValue}\n";}// 写入修改后的内容到文件File.WriteAllText(path, updatedContent);}catch (Exception ex){MessageBox.Show("异常:" + ex.Message);return false;}return true;}

执行效果:修改键为R1的值为123

http://www.dtcms.com/a/293388.html

相关文章:

  • 【世纪龙科技】电动汽车原理与构造-汽车专业数字课程资源
  • [c++11]final和override
  • 黄山派lvgl8学习笔记(2)导入头文件和新建一个按钮控件
  • 标记语言---XML
  • linux 驱动-power_supply 与 mtk 充电框架
  • 工业互联网时代,如何通过混合SD-WAN提升煤炭行业智能化网络安全
  • 【Pytorch】数据集的加载和处理(一)
  • 使用ubuntu:20.04和ubuntu:jammy构建secretflow环境
  • ndarray的创建(小白五分钟从入门到精通)
  • 嵌入式开发学习(第三阶段 Linux系统开发)
  • 数据资产——解读数据资产全过程管理手册2025【附全文阅读】
  • [c++11]constexpr
  • 考研数据结构Part1——单链表知识点总结
  • 陷波滤波器设计全解析:原理、传递函数与MATLAB实现
  • Netty中AbstractReferenceCountedByteBuf对AtomicIntegerFieldUpdater的使用
  • 威胁情报:Solana 开源机器人盗币分析
  • Automotive SPICE
  • git的版本冲突
  • 大模型——Data Agent:超越 BI 与 AI 的边界
  • 用ESP32打造全3D打印四驱遥控车:无需APP的Wi-Fi控制方案
  • 从0开始的中后台管理系统-2
  • 课题学习笔记2——中华心法问答系统
  • 汽车行业数字化——解读52页汽车设计制造一体化整车产品生命周期PLM解决方案【附全文阅读】
  • 记录更新时间用java的new date还是数据库的now
  • 深入理解 C 语言数据类型:从内存到应用的全面解析
  • CAN基础知识 - 进阶版
  • 消息推送功能设计指南:精准触达与用户体验的平衡之道
  • Spring Boot 中集成ShardingSphere-JDBC的基本使用
  • Kibana报错[security_exception] current license is non-compliant for [security]
  • HCIA/IP(一二章)笔记