Answer the question
In order to leave comments, you need to log in
How to keep track of a file?
Good day.
Essence of the question: you need to monitor changes in the file, or rather, when new lines are added to it.
It is clear that you need to use FileSystemWatch, StreamReader, but the bottom line is that when saving a file, for some reason, the Changed event is triggered twice on FileSystemWatch, and reading from a file for some reason gives an empty line first, and then new lines from the file.
The code:
static void Main()
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory);
var file = Path.Combine(path, "1.txt");
var fsw = new FileSystemWatcher(path, "1.txt");
fsw.Changed += Sfw_Changed;
fsw.NotifyFilter = NotifyFilters.LastWrite;
fsw.EnableRaisingEvents = true;
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //открываем для чтения, но не блокируем файл.
sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.End); //Прыгаем в конец, старые данные нам не интересны.
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
autoResetEvent.WaitOne();
}
private static void Sfw_Changed(object sender, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed)
{
Console.WriteLine(e.ChangeType);
while (!sr.EndOfStream)
{
Console.WriteLine(sr.ReadLine());
}
}
}
Answer the question
In order to leave comments, you need to log in
Solution:
1) After adding all new lines in the file, add a new line (empty);
2) A feature of Notepad ++, it is called once through the system notepad;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question