替换文本文件中的文本不会在文件夹中更改

时间:2016-09-23 08:39:28

标签: c# text-files

使用此代码将索引更改为1到50001,50002等。但它似乎没有保存在文本文件中。 有没有办法说file.Save?或者我在做些傻事。

这是我的代码

  int count = 50000;
        string line;

        //string str = File.ReadAllText();
        System.IO.StreamReader file =
        new System.IO.StreamReader(@"C:\Documents\new\example\example.txt");
        while ((line = file.ReadLine()) != null)
        {
            line = line.Replace(":1}}", ":" + count + "}}");
            count++;
        }

2 个答案:

答案 0 :(得分:1)

您必须将更改的数据写回

  string path = @"C:\Documents\new\example\example.txt";

  int count = 50000; 

  var target = File
    .ReadLines(path)
    .Select(line => line.Replace(":1}}", ":" + count++ + "}}")) 
    .ToList(); // materialization required if you want to write back to the same file

  // You can here inspect, debug etc., what you're going to write back, e.g.
  // Console.Write(string.Join(Environment.NewLine, target));

  File.WriteAllLines(path, target);

答案 1 :(得分:0)

 int count = 50000;

        //string str = File.ReadAllText();
        string fileName = @"C:\Documents\new\example\example.txt";
        List<string> lines = new List<string>();

        using (System.IO.StreamReader file =
                    new System.IO.StreamReader(fileName))
        {
            string line;
            while ((line = file.ReadLine()) != null)
            {
                line = line.Replace(":1}}", ":" + count + "}}");
                lines.Add(line);                    
                count++;
            }
        }

        using (StreamWriter sw = new StreamWriter(fileName,false))
        {
            foreach (string line in lines)
            {
                sw.WriteLine(line);
            }
        }