Mega Code Archive

 
Categories / C# / File Stream
 

Replace String In File

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Collections.Specialized; using System.Diagnostics; public static class FileUtils {     public static void ReplaceStringInFile(string fileName, string source, string target)     {         try         {             StreamReader streamReader = null;             StreamWriter streamWriter = null;             string contents = null;             streamReader = File.OpenText(fileName);             contents = streamReader.ReadToEnd();             streamReader.Close();             streamWriter = File.CreateText(fileName);             streamWriter.Write(contents.Replace(source, target));             streamWriter.Close();         }         catch (Exception ex)         {             Trace.TraceError("File I/O Error: {0}, StackTrace: {1}", ex.Message, ex.StackTrace);         }     } }