Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a file and replace strings in C#

Tags:

string

c#

file

I'm trying to figure out the best way to open an existing file and replace all strings that match a declared string with a new string, save it then close.

Suggestions ?

like image 530
Gabe Avatar asked Dec 16 '09 16:12

Gabe


People also ask

How do I replace a string in a file?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do you find and replace a word in a string in C?

The fastest way would be to allocate a new string that is strlen (s) - strlen (word) + strlen (rpwrd) + 1 . Then use the strstr function to find the word to be replaced and copy up to that point into a new string, append the new word, then copy the rest of the original sentence into a new string.


2 Answers

Can be done in one line:

File.WriteAllText("Path", Regex.Replace(File.ReadAllText("Path"), "[Pattern]", "Replacement")); 
like image 127
Matthias Avatar answered Oct 01 '22 15:10

Matthias


If you're reading large files in, and you string for replacement may not appear broken across multiple lines, I'd suggest something like the following...

private static void ReplaceTextInFile(string originalFile, string outputFile, string searchTerm, string replaceTerm) {     string tempLineValue;     using (FileStream inputStream = File.OpenRead(originalFile) )     {         using (StreamReader inputReader = new StreamReader(inputStream))         {             using (StreamWriter outputWriter = File.AppendText(outputFile))             {                 while(null != (tempLineValue = inputReader.ReadLine()))                 {                     outputWriter.WriteLine(tempLineValue.Replace(searchTerm,replaceTerm));                 }             }         }     } } 

Then you'd have to remove the original file, and rename the new one to the original name, but that's trivial - as is adding some basic error checking into the method.

Of course, if your replacement text could be across two or more lines, you'd have to do a little more work, but I'll leave that to you to figure out. :)

like image 39
ZombieSheep Avatar answered Oct 01 '22 16:10

ZombieSheep