내 pfirewall.log를 모니터링 할 수있는 작은 프로그램을 만들려고하는데 열 수없는 것 같습니다. 이 파일은 항상 이미 다른 프로세스에 의해 열린 것으로 보인다 : 나는 모든 좀 여기서 문제는메모장 ++처럼 항상 열려있는 로그 파일을 모니터링하는 방법은 무엇입니까?
// use FilesystemWatcher
// open FileStream
// read from last position to end
// output new lines
말, 꽤 많은 (단순) 답을 발견했다. 메모장 ++에서 보여 주듯이, 필자는 항상 윈도우에 파일을 쓰는 프로세스라고 생각합니다.
즉, Notepad ++는 내가 할 수없는 일을 할 수 있습니다. 이미 열었음에도 불구하고 파일을 읽으십시오.
public FirewallLogMonitor(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException("Logfile not found");
this.file = path;
this.lastPosition = 0;
this.monitor = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
this.monitor.NotifyFilter = NotifyFilters.Size;
}
그리고 monitor.Changed 이벤트에 파일을 읽으려고 :
나는 생성자에서 내 모니터를 초기화 나에게 파일을 말할 수 그것은 항상 new FileStream(...)
에 IOException가 발생
private void LogFileChanged(object sender, FileSystemEventArgs e)
{
using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader reader = new StreamReader(stream))
{
stream.Seek(this.lastPosition, SeekOrigin.Begin);
var newLines = reader.ReadToEnd();
this.lastPosition = stream.Length;
var filteredLines = filterLines(newLines);
if (filteredLines.Count > 0)
NewLinesAvailable(this, filteredLines);
}
}
을 이미 사용 중입니다.
메모장 + +가 있기 때문에 내가 할 수있는 방법이 있어야합니다. 맞습니까?
** 편집 : ** A 버튼이하는이 :
public void StartLogging()
{
this.IsRunning = true;
this.monitor.Changed += LogFileChanged;
this.monitor.EnableRaisingEvents = true;
}
** Edit2가 : 그 사람이 내가 쓰기 과정을 제어 할 수 있다고 가정하기 때문에 **이, FileMode and FileAccess and IOException: The process cannot access the file 'filename' because it is being used by another process의 중복이 아니다. 다른 제안을 시도하고 결과를보고합니다.
는'FileShare.Read'는 "읽기 파일의 이후 개방을 할 수 있습니다"를 의미한다. 파일이 이미 쓰기 위해 열렸 으면 작동하지 않습니다. 'FileShare.ReadWrite | FileShare.Delete'는 다른 사용자가 파일을 통해 할 수있는 일을 최대한으로 허용합니다. –
[안전하지 않은 모드에서 C#으로 잠긴 파일을 읽는 가장 간단한 방법은 무엇입니까?] (http://stackoverflow.com/q/3560651/669576) –
'FileShare'를 수정하여 예외적으로 파일을 소유하고있는 다른 프로세스가 새로운 로그 라인을 작성하기 위해 그것을 잠그면'var newLines = reader.ReadToEnd()'에 예외를 무작위로 얻을 것이다. 이는 간헐적으로 * Windows가 파일에 기록해야하는시기에 따라 다릅니다. 즉, 예외가 표시되기까지 몇 주가 걸릴 수 있습니다. 'try/catch'와 실패한 읽기로부터 복구하는 방법이 필요합니다. – Quantic