mrblah
mrblah

Reputation: 103497

Formatting a text file, how to update the file after I finished parsing it?

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?

Upvotes: 0

Views: 505

Answers (4)

jason
jason

Reputation: 241641

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);
}

Upvotes: 2

Fredrik Mörk
Fredrik Mörk

Reputation: 158309

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

Upvotes: 2

Matthias Wandel
Matthias Wandel

Reputation: 6483

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

Upvotes: 0

rein
rein

Reputation: 33445

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.

Upvotes: 0

Related Questions