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

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

cs 复制代码
        /// <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);

            }



        }

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

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

cs 复制代码
 /// <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的值

通过键修改文件中的值

cs 复制代码
      /// <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

相关推荐
小陈工12 小时前
Python Web开发入门(十七):Vue.js与Python后端集成——让前后端真正“握手言和“
开发语言·前端·javascript·数据库·vue.js·人工智能·python
rockey62716 小时前
AScript如何实现中文脚本引擎
c#·.net·script·eval·expression·function·动态脚本
一定要AK17 小时前
Spring 入门核心笔记
java·笔记·spring
A__tao17 小时前
Elasticsearch Mapping 一键生成 Java 实体类(支持嵌套 + 自动过滤注释)
java·python·elasticsearch
KevinCyao17 小时前
java视频短信接口怎么调用?SpringBoot集成视频短信及回调处理Demo
java·spring boot·音视频
科技小花17 小时前
数据治理平台架构演进观察:AI原生设计如何重构企业数据管理范式
数据库·重构·架构·数据治理·ai-native·ai原生
一江寒逸17 小时前
零基础从入门到精通MySQL(中篇):进阶篇——吃透多表查询、事务核心与高级特性,搞定复杂业务SQL
数据库·sql·mysql
D4c-lovetrain17 小时前
linux个人心得22 (mysql)
数据库·mysql
迷藏49417 小时前
**发散创新:基于Rust实现的开源合规权限管理框架设计与实践**在现代软件架构中,**权限控制(RBAC)** 已成为保障
java·开发语言·python·rust·开源
阿里小阿希18 小时前
CentOS7 PostgreSQL 9.2 升级到 15 完整教程
数据库·postgresql