Could someone tell me what is the best way to check for a new Line in a Text file? I have a scale, it writes weight values into a text file. Then my C# program has to read out the last value und use it for other calculation. I would read the last line of the text and repeat this after few seconds, but this is a bad solution because it would be better if I could read the last value only then when a new value has been written to file, not every few seconds. So how do I check for a new line in a file? Should I use the file date or file size? Whats the best way? Hope someone can help.
while (checkBox1.Checked)
{
//Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\";
/* Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = @"Textdokument.txt";
watcher.Changed += new FileSystemEventHandler(OnChanged);
}
}
private void OnChanged(object source, FileSystemEventArgs e)
{
textBox1.Text = "1234";
if (e.ChangeType == WatcherChangeTypes.Changed)
{
string lastLine = File.ReadLines(e.FullPath).Last();
textBox1.Text = lastLine;
}
}
This is my code until now. No Errors are shown but still nothing happens. Could it be that the problem is that the other application is writing into the file while I want to read from it? It shouldnt be a problem, or am I wrong?