As
mentioned by Kubajzz, reading a file that is being edited at the same time may have the possibility of yielding unexpected results.
If you wish to edit files as they are being edited, your best bet is to use
FileSystemWatcher class:
using System;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main(string[] args)
{
string filePath = "full_path_to_your_file.txt";
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = Path.GetDirectoryName(filePath);
watcher.Filter = Path.GetFileName(filePath);
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Changed += OnFileChanged;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Press Enter to exit.");
Console.ReadLine();
}
private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
string filePath = e.FullPath;
try
{
string fileContent = File.ReadAllText(filePath);
string updatedContent = StringManipulationStuff(fileContent);
File.WriteAllText(filePath, updatedContent);
}
catch (Exception ex)
{
}
}
private static string StringManipulationStuff(string input)
{
string pattern = @"\btwo\b";
string replacement = "twotest";
return Regex.Replace(input, pattern, replacement);
}
}