I'm trying to figure out which process causes exception that the file is used by another process. So the only checking I'm trying to do is if I found this process, this code does not shows me the note that the "File used by another process!"
try
{
using (Stream stream = new FileStream(doc.txt, FileMode.Open))
{
/// Writing place to doc.txt which throws exception sometimes
}
}
catch
{
textBox1.AppendText("File used by another process!");
}
The place where the exception throws program into the error is writing into the file
using (StreamWriter sw = File.AppendText(doc.txt))
sw.WriteLine(text);
So what I did, first of all, I found all my requests to the file to be sure that is closed sw.Close()
:
StreamWriter sw = File.AppendText(doc.txt);
sw.WriteLine(text);
sw.Close();
and same for:
using (StreamReader sr = new StreamReader(doc.txt))
{
// some code
sr.Close();
}
also I have there, and I'm not sure how if I need to close it too:
File.WriteAllText(doc.txt, text);
and:
if (File.Exists(doc.txt))
wordsTyped.AddRange(File.ReadAllLines(doc.txt));
But nothing helps
How is possible to know which process used file, or how to stop it?
I don't asking how to avoid it or prevent because it always use, so have constant risk of exception.
What else can cause this problem except given attempts if it is done correctly?