@Markus Freitag , Welcome to Microsoft Q&A, you could refer to the following steps to detect if the file changes and get the changed text.
First, Please create the duplicate of your files.
Second, Please use FileSystemWatcher to detect if the file has been changed.
Third, you could use DiffMatchPatch API(install nugetpackage DiffMatchPatch) to get the difference between two files.
Finally, Please reset the duplicate of the file.
Code example:
static string path = "E:\\Test";
static void Main(string[] args)
{
foreach (var item in Directory.GetFiles(path))
{
Console.WriteLine(item);
string path = item.Replace(Path.GetFileNameWithoutExtension(item), Path.GetFileNameWithoutExtension(item) + "copy");
if(!File.Exists(path))
{
File.Copy(item, item.Replace(Path.GetFileNameWithoutExtension(item), Path.GetFileNameWithoutExtension(item) + "copy"));
}
}
var watcher = new FileSystemWatcher(path);
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
watcher.Changed += OnChanged;
watcher.Filter = "*.xml";
watcher.IncludeSubdirectories = true;
watcher.EnableRaisingEvents = true;
Console.ReadKey();
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed)
{
Console.WriteLine($"Changed: {e.FullPath}");
string path1 = e.FullPath.Replace(Path.GetFileNameWithoutExtension(e.FullPath), Path.GetFileNameWithoutExtension(e.FullPath)+"copy");
var ori = File.ReadAllText(path1);
var current = File.ReadAllText(e.FullPath);
diff_match_patch dmp = new diff_match_patch();
List<Diff> diff = dmp.diff_main(ori, current);
dmp.diff_cleanupSemantic(diff);
for (int i = 0; i < diff.Count; i++)
{
if (diff[i].operation.ToString()=="DELETE")
{
Console.WriteLine(diff[i].text+"has changed to"+ diff[i+1].text);
}
}
File.Delete(path1);
File.Copy(e.FullPath, path1);
}
}
Based on my test, it works well.
Best Regards,
Jack
If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.