The code below writes to a text file in a while loop and sometimes it will produce an error saying that the "The process cannot access the file because its being used by another process" etc..." The error usually happens on "using (FileStream fs = File.OpenRead(filePath)) " Is there a way to check the file is no longer being used or a way to dispose of the text writer properly?
if (File.Exists(filePath))
{
TextWriter sud = File.AppendText(filePath);
sud.WriteLine(GenericLIST[testloop].ToString());
sud.Close();
sud.Dispose();
using (FileStream fs = File.OpenRead(filePath))
{
using (StreamReader sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
richTextBox1.AppendText(sr.ReadLine());
}
}
}
}
else
{
TextWriter sud = new StreamWriter(filePath);
sud.WriteLine(GenericLIST[testloop].ToString());
sud.Close();
sud.Dispose();
}