Below shows the method that replace a text in files within a directory which is iteratively searched:
public void ReplaceInFiles(string dir_path, Dictionary<string, Dictionary<int, string>> results, string old_text, string new_text, string extension=null)
{
DirectoryInfo dir = new DirectoryInfo(dir_path);
DirectoryInfo[] sub_dirs = dir.GetDirectories();
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string file_path=file.FullName;
if (!string.IsNullOrEmpty(extension) && file.Extension != extension) continue;
Dictionary<int, string> found_locations = null;
using (StreamReader reader = new StreamReader(file.OpenRead()))
{
string line;
int line_index=0;
while ((line = reader.ReadLine()) != null)
{
line_index++;
if (line.Contains(old_text))
{
if (results.ContainsKey(file_path))
{
found_locations = results[file_path];
}
else
{
found_locations = new Dictionary<int, string>();
results[file_path] = found_locations;
}
found_locations[line_index] = line;
}
}
}
if(found_locations!=null)
{
string file_content=null;
using(StreamReader reader =new StreamReader(file.OpenRead()))
{
file_content=reader.ReadToEnd();
}
file_content=file_content.Replace(old_text, new_text).TrimEnd(Environment.NewLine.ToCharArray());
using(StreamWriter writer=new StreamWriter(file.OpenWrite()))
{
writer.WriteLine(file_content);
writer.Flush();
}
}
}
foreach (DirectoryInfo sub_dir in sub_dirs)
{
string sub_dir_path=sub_dir.FullName;
ReplaceInFiles(sub_dir_path, results, old_text, new_text, extension);
}
}
Below is the code snippet which shows how to use the method above:
string dir_path="C:\temp";
string text_to_find="SimuKit.DomainModels\";
string text_to_replace="packages\SimuKit.DomainModels\";
string extension=".sln";
Dictionary<string, Dictionary<int, string>> results=new Dictionary<string, Dictionary<int, string>>();
ReplaceInFiles(dir_path, results, text_to_find, text_to_replace, extension);
foreach (string file_path in results.Keys)
{
Dictionary<int, string> line_content = results[file_path];
foreach (int line_index in line_content.Keys)
{
Console.writeline("{0} is replaced in file {1} in line {2}, original content: {3}", text_to_find, file_path, line_index, line_content[line_index]);
}
}
No comments:
Post a Comment