0

I have program that write its errors in text file, when this program catches error, it appends it to a text file, I want to make small program to detect errors one by one from a text file, when program write an errors.

I use this way:

string ErrorsFilePath = @"D:\A.txt"; // example path
long oldLength = 0;
long newLength = 0;
while (true)
{
   FileInfo fi = new FileInfo(ErrorsFilePath);
   newLength = fi.Length;
   if (newLength > oldLength)
   {
      GC.Collect();
      string txtAllErrors = File.ReadAllText(ErrorsFilePath);
      int startIndex = (int)oldLength;
      int length = (int)(newLength - oldLength);
      ErrorDetected(txtAllErrors.Substring(startIndex, length));
      oldLength = newLength;
   }
   Thread.Sleep(10);
   GC.Collect();
}

Are there a way to detect text file changes on its content?, Like events fires when text file changes, and give me the different text changes.

Abdullah Zaid
  • 171
  • 3
  • 9
  • Try [FileSystemWatcher](http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx) – Aron Jun 04 '14 at 08:31

2 Answers2

1

The FileSystemWatcher class will give you part of what you need - it will fire events when a file changes. Take a look here:

http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

kobigurk
  • 731
  • 5
  • 14
1

You can use a FileSystemWatcher instance for this.

http://msdn.microsoft.com/en-US/en-en/library/system.io.filesystemwatcher.aspx

Why do you call GC.Collect so often?

Oscar
  • 13,594
  • 8
  • 47
  • 75
  • I use CG.Collect because it maybe clears any related data in memory while looping process. thank you for your solution... – Abdullah Zaid Jun 04 '14 at 10:45
  • You should let the system decide when to collect memory at least that you have a good reason, and this doesn't seems a good one. If you want to preserve memory, instead of calling GC.Collect, use a StringBuilder instead of string concatenation. – Oscar Jun 04 '14 at 11:05
  • You are right . Thank you very much ... – Abdullah Zaid Jun 04 '14 at 13:31