如何连续阅读文本文件

Adi*_*Adi 2 c# filesystemwatcher file-handling text-files

我有一个文本文件,每次都从服务器数据更新.现在按照我的要求,我必须逐行读取这个文件.我知道如何逐行读取文件,但不知道如何连续读取它.这是我的c#代码逐行读取文件...

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

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

                while ((line = reader.ReadLine()) != null)
                {
                   //Do Processing
                }
              }
         }
Run Code Online (Sandbox Code Playgroud)

根据我的要求,我必须连续观看文本文件以进行更改.假设已在文本文件中添加了一个新行,添加它的那一刻应该由上面定义的代码读取,并且应该根据条件执行处理.

Adi*_*dil 5

您可以使用FileSystemWatcher侦听文件系统更改通知,并在目录或目录中的文件时引发事件.如果文本附加在文本文件中但未修改,则可以跟踪已读取的行号,并在触发更改事件后继续跟踪.

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;
}
Run Code Online (Sandbox Code Playgroud)