Hi,
I've a windows service writes its log in a text file in a simple format, Now, I'm going to create a small software to read the service's log and show the existing log and the added as live view,
the problem is when the service will lock the text file while adding the new lines, and the viewer application will lock the file while reading,
The Service Code:
void WriteInLog(string logFilePath, data)
{
File.AppendAllText(logFilePath, , string.Format("{0} : {1}\r\n", DateTime.Now, data));
}
The viewer Code:
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))
{
for (int i = 0; i < index ; i++) // skipping the old data, it has read in the Form1_Load event handler
sr.ReadLine();
while (sr.Peek() >= 0) // reading the live data if exists
{
string str = sr.ReadLine();
if (str != null)
{
AddLineToGrid(str);
index++;
}
}
sr.Close();
}
}
Is there any problem in my code in reading and writing way?
How can I prevent the problem ?
Thanks in advance.