1

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?

nikorio
  • 671
  • 4
  • 16
  • 28
  • I don't think you will have to explicitly close the file when you are using `using`. – Prajwal Jan 05 '17 at 04:27
  • It's certainly possible becuase one can enumerate all the handles (including files) that a process has open. e.g. _[Process Explorer](https://technet.microsoft.com/en-us/sysinternals/processexplorer.aspx)_ does just that. So perhaps enumerate all open processes, then the handles for each. [This question](http://stackoverflow.com/questions/733384/how-to-enumerate-process-handles) may be useful –  Jan 05 '17 at 04:31
  • Are you running them in different threads? – Prajwal Jan 05 '17 at 04:34
  • @Prajwal Hello, I have all in: using (StreamWriter sw = File.AppendText(doc.txt)) sw.WriteLine(text); and then I put it out of using, but result is same. File in using, and I have no idea what is the reason, there is a lot of such requests as it show above, but no one can't be active at the moment of writing in the exception place, but fact is it is in process. – nikorio Jan 05 '17 at 04:35

0 Answers0