Fast way to change txt file and save it

You could keep WriteAllLines and use ReadAllLines:

  1. ReadAllLines to get all lines as an array of strings
  2. Enumerate the array and use string.Replace to replace its content, line by line
  3. WriteAllLines and overwrite existing file

Or you could use stream reader/writer and read/write line by line. You currently are building a string with millions of concatenations, that's the performance issue.

That being said, you probably have an obvious security issue here. Why was critical information such as credit card numbers stored as plain text in the first place?


Your primary problem here is that you're appending to a string. And that gets expensive very quickly. You should be able to process that 65 MB in about five seconds. Here's what I would do:

string outputFileName = "temp.txt";
using (var outputFile = new StreamWriter(outputFileName))
{
    foreach (var line in File.ReadLines(inputFileName))
    {
        var newLine = line.Substring(0, 124) + "************" +
                    line.Substring(136, lineOfText.Length - 136);
        outputFile.WriteLine(newLine);
    }
}

This is going to be a lot faster than appending strings. If you really want to do it all in memory, then use a StringBuilder. Instead of

string NewTextFile = "";

Use

StringBuilder NewTextFile = new StringBuilder();

And when you're composing the output, replace the string concatenation with:

NewTextFile.AppendLine(
    lineOfText.Substring(0, 124) + "************" +
    lineOfText.Substring(136, lineOfText.Length - 136));

Finally, to write it to the file:

System.IO.File.WriteAllText(NewPath, NewTextFile.ToString());