Windows 서비스에서 로그를 간단한 형식으로 텍스트 파일에 기록합니다.어떻게 텍스트 파일을 잠그지 않고 읽을 수 있습니까?
이제 서비스의 로그를 읽도록 작은 응용 프로그램을 만들고 기존 로그와 추가 된 로그를 모두 라이브 뷰로 표시합니다.
문제는 서비스가 새 줄을 추가하기 위해 텍스트 파일을 잠그는 동시에 뷰어 응용 프로그램이 파일을 읽기 위해 잠그는 것입니다.
서비스 코드 :
void WriteInLog(string logFilePath, data)
{
File.AppendAllText(logFilePath,
string.Format("{0} : {1}\r\n", DateTime.Now, data));
}
뷰어 코드 : 읽기 및 방법을 서면으로 내 코드에 문제가
int index = 0;
private void Form1_Load(object sender, EventArgs e)
{
try
{
using (StreamReader sr = new StreamReader(logFilePath))
{
while (sr.Peek() >= 0) // reading the old data
{
AddLineToGrid(sr.ReadLine());
index++;
}
sr.Close();
}
timer1.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
using (StreamReader sr = new StreamReader(logFilePath))
{
// skipping the old data, it has read in the Form1_Load event handler
for (int i = 0; i < index ; i++)
sr.ReadLine();
while (sr.Peek() >= 0) // reading the live data if exists
{
string str = sr.ReadLine();
if (str != null)
{
AddLineToGrid(str);
index++;
}
}
sr.Close();
}
}
있습니까?
어떻게 문제를 해결할 수 있습니까?
[StreamReader가 사용 중일 때 StreamReader가 잠기는 것을 방지 할 수 있습니까?] (https://stackoverflow.com/questions/1606349/can-i-prevent-a-streamreader-from-locking) -a-text-file-while-is-use) –