Skip to content

Commit

Permalink
Fixing bugs with file occupied by another process
Browse files Browse the repository at this point in the history
When the contents of the file were changed by various processes, an undefined exception occurred.

Problem solved.
  • Loading branch information
smiell committed May 22, 2024
1 parent 452b3c1 commit d35d8de
Showing 1 changed file with 26 additions and 7 deletions.
33 changes: 26 additions & 7 deletions LogsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,35 @@ private void StartFileWatcher(string path)
// Method handles file change
private void FileChanged(object sender, FileSystemEventArgs e)
{
// Get file, open content and load as richbox string
string text = File.ReadAllText(filePath);
Invoke(new Action(() =>
// Define a helper function to read the file that will retry when an exception is received
Action<string> readFile = null;
readFile = (filePath) =>
{
richTextBox1.Text = text;
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.ScrollToCaret();
}));
try
{
// Read file
string text = File.ReadAllText(filePath);
// Load file as richTextBox1.text
Invoke(new Action(() =>
{
richTextBox1.Text = text;
richTextBox1.SelectionStart = richTextBox1.TextLength;
richTextBox1.ScrollToCaret();
}));
}
catch (IOException ex)
{
// Handle Exception
Thread.Sleep(500); // Wait 500ms before next try to load file again
readFile(filePath);
}
};

// Handle helper method to load file
readFile(filePath);
}


private void button2_Click(object sender, EventArgs e)
{
// Empty rich box string
Expand Down

0 comments on commit d35d8de

Please sign in to comment.