tags:

views:

56

answers:

4

How would I open a file, perform some regex on the file, and then save the file?

I know I can open a file, read line by line, but how would I update the actual contents of a file and then save the file?

A: 

Open the file for read. Read all the contents of the file into memory. Close the file. Open the file for write. Write all contents to the file. Close the file.

Alternatively, if the file is very large:

Open fileA for read. Open a new file (fileB) for write. Process each line of fileA and save to fileB. Close fileA. Close fileB. Delete fileA. Rename fileB to fileA.

rein
A: 

Close the file after you finish reading it
Reopen the file for write
Write back the new contents

Matthias Wandel
+2  A: 

The following approach would work regardless of file size, and will also not corrupt the original file in anyway if the operation would fail before it is complete:

string inputFile = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "temp.txt");
string outputFile = Path.Combine(Environment.GetFolderPath(
        Environment.SpecialFolder.MyDocuments), "temp2.txt");
using (StreamReader input = File.OpenText(inputFile))
using (Stream output = File.OpenWrite(outputFile))
using (StreamWriter writer = new StreamWriter(output))
{
    while (!input.EndOfStream)
    {
        // read line
        string line = input.ReadLine();
        // process line in some way

        // write the file to temp file
        writer.WriteLine(line);
    }
}
File.Delete(inputFile); // delete original file
File.Move(outputFile, inputFile); // rename temp file to original file name
Fredrik Mörk
amazing, thanks a bunch.
mrblah
+2  A: 
string[] lines = File.ReadAllLines(path);
string[] transformedLines = lines.Select(s => Transform(s)).ToArray();
File.WriteAllLines(path, transformedLines);

Here, for example, Transform is

public static string Transform(string s) {
    return s.Substring(0, 1) + Char.ToUpper(s[1]) + s.Substring(2);
}
Jason
Potentially loading **a lot** of data into memory at once.
Roman Boiko
it is nice and short, my file isn't that big. nice one jason.
mrblah
(Agree with mrblah, it was just a warning... maybe not very useful though). +1
Roman Boiko
@Roman: Potentially, yes. But for reasonably sized files it's short, simple and to the point. KISS.
Jason