首页 > 解决方案 > 如何通过 C# 修改 txt 文件的某些部分

问题描述

我正在尝试从 C# 访问和修改 txt 文件的某些部分。

我有一个 Game.txt 文件,它目前只有两行,每行只有 5 个单词。以下是我所拥有的:

第 1 行:Rick Sanchez rick@gmail.com 剑火

第 2 行:约翰·史密斯 john@gmail.com 屏蔽水

我想检查这个 Game.txt 文件的内容是否有电子邮件 rick@gmail.com,如果有,那么我想用头盔重写/替换词剑。以下是我尝试过的,我目前被卡住了。任何帮助表示赞赏:

string[] words = File.ReadAllLines(@"C:\folder\Game.txt");
for (int i = 0 ; i < words.count() ; i++)
    {
       if(words[i].Contains("rick@gmail.com"))
       {
          string[] rowDetail = words[i].Split(' ');
          rowDetail[3]=helmet; // This only writes it in RAM; not in Game.txt file

    // Alternatively I tried below but it seems to overwrite on top of the entire txt file and wipe out all data:

          FileStream fs = File.Create(@"C:\folder\Game.txt");    
          Byte[] info = new UTF8Encoding(true).GetBytes("helmet");
          fs.Write(info, 0, info.Length);
          fs.Close();
       }
    }

标签: c#

解决方案


这可能不是你的家庭作业的本意,但如果找到电子邮件,这将用头盔替换所有剑的出现

 string words = File.Read(@"C:\folder\Game.txt");
   
 if((words.Contains("rick@gmail.com"))
 {
    words = words.replace("sword","helmet");
 }

 FileStream fs = File.WriteAllText(@"C:\folder\Game.txt",words);    

推荐阅读