Question

I have a text file which is getting updated every time from the server data .Now as per my requirement i have to read this file line by line continuously.I know how to read a file line by line but not getting how to read it continuously.Here is my c# code to read file line by line...

if (System.IO.File.Exists(FileToCopy) == true)
        {

            using (StreamReader reader = new StreamReader(FileToCopy))
            {
                string line;
                string rawcdr;

                while ((line = reader.ReadLine()) != null)
                {
                   //Do Processing
                }
              }
         }

As per my requirement i have to watch a text file continuously for changes.Suppose a new line has been added into the text file,the moment it has added it should be read by above defined code and processing should be performed as per the conditions.

Was it helpful?

Solution

You can use FileSystemWatcher to listens to the file system change notifications and raises events when a directory, or file in a directory. If the text is appended in the text file but not modified then you can keep track of line numbers you have read and continue after that when change event is triggered.

private int ReadLinesCount = 0;
public static void RunWatcher()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = "c:\folder";   
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;   
    watcher.Filter = "*.txt";    
    watcher.Changed += new FileSystemEventHandler(OnChanged);
    watcher.EnableRaisingEvents = true;

}

private static void OnChanged(object source, FileSystemEventArgs e)
{
      int totalLines - File.ReadLines(path).Count();
      int newLinesCount = totalLines - ReadLinesCount;
      File.ReadLines(path).Skip(ReadLinesCount).Take(newLinesCount );
      ReadLinesCount = totalLines;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top