How can I elegantly implement multiple line replacements in a single file?

I currently have code for replacing lines in a file that looks like this:

File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));

However, each replacement opens and closes the file, and it seems that sometimes they start “too fast”, and one replacement will not work, because the file has not closed yet with the previous line replacement. Is there any code that I can reuse that solves this problem, possibly using the FileStream class (so that I can open and close once)? Or suggestions for a better way to do this? Just wondering if there is anything simpler than creating byte arrays of strings that I want to replace and writing code to read, write and search bytes manually. Thank.

+1
source share
6 answers
string contents = File.ReadAllText(filePath);
contents = Regex.Replace(contents,
    "( " + column.Key + " )",
    " " + column.Value + " ");
contents = Regex.Replace(contents,
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]");
File.WriteAllText(filePath, contents);
+2
source

It would be best practice to read the contents of the file once, storing it in a local variable. Then make any changes you need (in your case, two regular expressions), and then write this output to a file. File IO is one of the most expensive operations a computer can perform, and in-memory computing is much cheaper. Hit the drive as little as possible if you can avoid it.

+4
source

, :

 string text = File.ReadAllText(filePath);

 text = Regex.Replace(...);
 text = Regex.Replace(...);
 ...
 File.WriteAllText(filePath, text);

, . , , .

+3

It looks like you should do all your string replacements in a line in memory, and then write the final resulting line to disk.

+1
source
var fileContents = File.ReadAllText(filePath);
fileContents = Regex.Replace(fileContents,
    "( " + column.Key + " )",
    " " + column.Value + " "
);
fileContents = Regex.Replace(fileContents ,
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
);
File.WriteAllText(filePath, fileContents);
+1
source

Well, the easiest way is ReadAllTextto complete your replacements, then WriteAllText.

var text = File.ReadAllText(filePath);
text = Regex.Replace(text,"( " + column.Key + " )"," " + column.Value + " ");
text = Regex.Replace(text,"(\\[\"" + column.Key + "\"\\])","[\"" + column.Value + "\"]");
File.WriteAllText(text,filePath);
+1
source

All Articles