0

Been using this code to change the index of 1 to 50001, 50002 ect. But it doesn't seem to save in the text file. Is there a way to say file.Save? or am I doing something silly.

Here is my code

  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++;
        }
Nicola
  • 59
  • 7

2 Answers2

1

You have to write the changed data back:

  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);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • That looks much more cleaner than my approach ;-) – Mat Sep 23 '16 at 08:52
  • Amazing thanks. Is there any way you could search a file for all text file by using this... I have tired foreach (string file in Directory.EnumerateFiles(path, "*.txt", SearchOption.AllDirectories)) { – Nicola Sep 23 '16 at 09:08
  • 1
    @Nicola: yes, I suggest *extracting a method* for this: `public static void ChangeMyFile(string path) {/* the code from the answer here */}` and then you can use `foreach (string file in Directory.EnumerateFiles(path, "*.txt", SearchOption.AllDirectories)) {ChangeMyFile(file);}` – Dmitry Bychenko Sep 23 '16 at 09:13
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);
            }
        }
Mat
  • 1,960
  • 5
  • 25
  • 38