tags:

views:

66

answers:

3

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();
                    }
A: 

What happens here is that you release the file you were appending to read it again.

Between the sud.Close() and using(FileStream fs = File.OpenRead(filePath)) ANY other process running on your computer can take a look and a lock on your file. The Index service, or anti-viruses is often guilty of this.

Try to disable indexing on the folder, and see if your bug still happens so frequently.

Johan Buret
I will try this tomorrow as well, also do you think the while loop when writing the contents of the file to the richtextbox could be causing this error?
Mike
Since you don't release the lock in the while loop, it shouldn't happen
Johan Buret
A: 

It works for me. Are you using this file anywhere else? Perhaps you have another place in your code where you are missing a Dispose?

I'd also suggest that you use using consistently. There are a couple of places where you didn't and an exception thrown there could cause your file to not be disposed correctly.

Mark Byers
yes it works 75% of the time but I need it to work 100% or at least 95% of the time. also could you elaborate some on the use of "using" consistently as I don't think the code I posted could have another one without breaking something
Mike
+1  A: 

Use the excellent ProcMon and have it filter to all access done to the file and you should see which other process(es) are accessing the file. I've used it for this in the past and it's awesome for this.

http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx

James Manning