2016-06-22 5 views
4

삭제되고 다시 업데이트되는 모든 로그 파일을 지속적으로 감시하려고합니다.C# 지속적으로 재생되는 파일보기.

현재 나의 접근 방식은 FileSystemWatcher를 사용하는 것이 었습니다. 이 훌륭한 파일을 수정할 때 작동하지만 파일을 삭제하고 같은 이름 가진 새 파일을 만들 경우 추적을 중지합니다.

내 현재의 접근 방식 :

생성 및 삭제 작업은 FileSystemWatcher의 OnChanged 이벤트를 트리거하지 않기 때문이다
namespace LogReader 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Watch(); 

      while (true) 
      { 

      } 
     } 

     public static void Watch() 
     { 
      var watch = new FileSystemWatcher(); 
      watch.Path = @"C:\TEMP\test"; 
      watch.Filter = "test.txt"; 
      watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite; 
      watch.Changed += new FileSystemEventHandler(OnChanged); 
      watch.EnableRaisingEvents = true; 
     } 

     private static void OnChanged(object source, FileSystemEventArgs e) 
     { 
      if (e.FullPath == @"C:\TEMP\test\test.txt") 
      { 
       Console.Clear(); 
       Stream stream = File.Open(@"C:\TEMP\test\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 
       StreamReader streamReader = new StreamReader(stream); 
       var lines = streamReader.ReadToEnd(); 
       Console.Out.WriteLine(lines); 

       streamReader.Close(); 
       stream.Close(); 
      } 
     } 

    } 
} 
+4

작성 및 삭제도 볼 수 있습니다. – BugFinder

답변

4

. 그래서 당신은 다음과 같이 될 것입니다 해당 이벤트를 등록하고 같은 이벤트 핸들러 OnChanged을 할당해야합니다

watch.Created += new FileSystemEventHandler(OnChanged); 
watch.Deleted += new FileSystemEventHandler(OnChanged); 

당신은 FileSystemWatcher에 대한 자세한 내용은 This을 통해 갈 수 있습니다.

+0

네, 또한 NotifyFilters.CreationTime 필터를 추가해야했습니다. 감사. – RusinaRange

+0

만들기 이벤트에 대해서는 (https://msdn.microsoft.com/en-us/library/system.io.notifyfilters (v = vs.110) .aspx) 필요 없음 –

+0

파일 만들기가 트리거되지 않았습니다. LastAccess 또는 LastWrite로 변경되었습니다. – RusinaRange

1

파일 생성이 아닌 파일 변경 만보고있었습니다. 시계 기능을 이것으로 변경하면 문제가 해결되었습니다.

public static void Watch() 
    { 
     var watch = new FileSystemWatcher(); 
     watch.Path = @"C:\TEMP\test"; 
     watch.Filter = "test.txt"; 
     watch.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.CreationTime; //more options 
     watch.Created += new FileSystemEventHandler(OnChanged); 
     watch.Changed += new FileSystemEventHandler(OnChanged); 
     watch.EnableRaisingEvents = true; 
    }