Hello everyone,
So I had to make a little program for a test on school.
And this program needed to replace text in files.
You could choose between directories/subdirectories etc.
And some of you might need some help with that. So I decided to post it on HF.
Here is the class:
Please say what I could improve or what I did good 😊
So I had to make a little program for a test on school.
And this program needed to replace text in files.
You could choose between directories/subdirectories etc.
And some of you might need some help with that. So I decided to post it on HF.
Here is the class:
Code
public class FileReplace
{
public delegate void FileProcessed(string fileName, string replace, Dictionary<int, string> linesReplaced);
public event FileProcessed FileProcessedHandler;
public void Replace(string search, string replace, string path, bool subDirectories = false, bool caseSensitive = false)
{
if (Directory.Exists(path) || File.Exists(path))
{
if (Path.HasExtension(path))
{
ReplaceFile(path, search, replace, caseSensitive);
}
else
{
var files = Directory.GetFiles(path, "*.*", subDirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly);
foreach(var file in files)
{
ReplaceFile(file, search, replace, caseSensitive);
}
}
}
}
private void ReplaceFile(string path, string search, string replace, bool caseSensitive)
{
if (File.Exists(path))
{
var file = File.ReadAllLines(path);
search = caseSensitive ? path.ToLower() : search;
var linesReplaced = new Dictionary<int, string>();
for (int l = 0; l < file.Length; l++)
{
var line = caseSensitive ? file[l].ToLower() : file[l];
if (line.Contains(search))
{
file[l] = file[l].Replace(search, replace);
linesReplaced.Add(l, file[l]);
}
}
File.WriteAllLines(path, file);
FileProcessedHandler(path, replace, linesReplaced);
}
}
}Please say what I could improve or what I did good 😊


![[Image: 999WxIL.png]](https://i.imgur.com/999WxIL.png)

![[Image: Syr3DlV.png]](https://i.imgur.com/Syr3DlV.png)