[Solved] Replacing a certain word in a text file


If you don’t care about memory usage:

string fileName = @"C:\Users\Greg\Desktop\Programming Files\story.txt";
File.WriteAllText(fileName, File.ReadAllText(fileName).Replace("tea", "cabbage"));

If you have a multi-line file that doesn’t randomly split words at the end of the line, you could modify one line at a time in a more memory-friendly way:

// Open a stream for the source file
using (var sourceFile = File.OpenText(fileName))
{
    // Create a temporary file path where we can write modify lines
    string tempFile = Path.Combine(Path.GetDirectoryName(fileName), "story-temp.txt");
    // Open a stream for the temporary file
    using (var tempFileStream = new StreamWriter(tempFile)) 
    {
        string line;
        // read lines while the file has them
        while ((line = sourceFile.ReadLine()) != null) 
        {
            // Do the word replacement
            line = line.Replace("tea", "cabbage");
            // Write the modified line to the new file
            tempFileStream.WriteLine(line);
        }
    }
}
// Replace the original file with the temporary one
File.Replace("story-temp.txt", "story.txt", null);

1

solved Replacing a certain word in a text file