I am coding an app to read a game's chat log. The problem is that I get an error randomly, maybe the app works for 20 min or 30 min and suddenly get the error: System.IO.IOException: "The process cannot access the file 'fileDir' because it is being used by another process."
I know that the chat log is being used by the game but as I said I can read the lines or even delete the whole text after reaching 1,000 lines without problem until I get that error. I also can edit the file manually and save it while ingame.
private void start_Click(object sender, EventArgs e){
if (!_isRunning)
{
_isRunning = true;
StreamReader sr = new StreamReader(fileDir);
var lines = File.ReadAllLines(fileDir);
lastReadLine = lines.Length - 1; //start to read from the last line
sr.Close();
timer1.Start();
}
}
private void UpdateText()
{
try
{
StreamReader sr = new StreamReader(fileDir); // error here
var lines = File.ReadAllLines(fileDir);
sr.Close();
linesLength = lines.Length;
for (int i = lastReadLine; i < lines.Length; i++)
{
if (lines[i].Contains("You inflicted") || lines[i].Contains("The attack missed") || lines[i].Contains("The target Dodged"))
{
totalAttacks++;
}
lastReadLine = i + 1;
}
if (linesLength >= linesMax)
{
try
{
if (File.Exists(fileDir))
{
TextWriter tw = new StreamWriter(fileDir, false); //error here 1 time
lastReadLine = 0;
tw.Close();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
}
The timer executes the UpdateText() 1 times per second. It's my first app with Visual Studio and I am also newbie with C#, I hope any experienced programmer knows what's wrong.
Thank you.