当前位置: 首页 > 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.lryc.cn/news/596383.html

相关文章:

  • Java学习-------事务失效
  • 从“点状用例”到“质量生态”:现代软件测试的演进、困局与破局
  • Vue3 学习教程,从入门到精通,Vue3 循环语句(`v-for`)语法知识点与案例详解(13)
  • C# 属性
  • XSS(跨站脚本)
  • CPU 密集型 和 I/O 密集型 任务
  • 达梦数据库表字段增加时报错[-2106]:无效的表或视图名,[-2116]:列[IS_REPEAT]已存在
  • 【C++】第十八节—一文万字详解 | map和set的使用
  • 如何搭建appium工具环境?
  • Go的异常处理+文件处理
  • JAVA API (三):从基础爬虫构建到带条件数据提取 —— 详解 URL、正则与爬取策略
  • M3088NL是一款网络滤波器/变压器支持100M和1000M网络环境,适用于高速网络传输场景M3088
  • 在腾讯云上安装gitlab
  • HCIP第一二章笔记整理
  • 网络基础DAY16-MSTP-VRRP
  • 公司内部网址怎么在外网打开?如何让外网访问内网的网站呢?
  • 5G工业路由器如何凭借高性价比助力多行业数字化转型?
  • Hugging Face 模型的缓存和直接下载有什么区别?
  • TI DLP3010光机与相机触发使用指南
  • Android app如果不适配Android 15会怎么样
  • 一款基于 WPF 开源、功能全面的串口调试工具
  • 【Spark征服之路-3.7-Spark-SQL核心编程(六)】
  • Aspose.Cells 应用案例:法国能源企业实现能源数据报告Excel自动化
  • 中国科技信息杂志中国科技信息杂志社中国科技信息编辑部2025年第14期目录
  • stm32 智能小车
  • vue2使用v-viewer实现自动预览
  • S2B2C电子商务模式介绍
  • 【Pytest】从配置到固件的使用指南
  • Vue底层换成啥了?如何更新DOM的?
  • YOLO-实例分割头