Tengo un servicio de Windows escribe su registro en un archivo de texto en un formato simple.¿Cómo puedo leer un archivo de texto sin bloquearlo?
Ahora, voy a crear una pequeña aplicación para leer el registro del servicio y mostrar tanto el registro existente como el agregado como vista en vivo.
El problema es que el servicio bloquea el archivo de texto para agregar las nuevas líneas y, al mismo tiempo, la aplicación del espectador bloquea el archivo para su lectura.
El código de servicio:
void WriteInLog(string logFilePath, data)
{
File.AppendAllText(logFilePath,
string.Format("{0} : {1}\r\n", DateTime.Now, data));
}
El Código espectador:
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();
}
}
¿Hay algún problema en mi código de lectura y escritura de manera?
¿Cómo resolver el problema?
Posible duplicado de [¿Puedo evitar que StreamReader bloquee un archivo de texto mientras está en uso?] (Https://stackoverflow.com/questions/1606349/can-i-prevent-a-streamreader-from-locking -a-text-file-while-it-is-in-use) –