开发者

What would cause this code to produce a file lock error?

The code below writ开发者_开发百科es 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();
                    }


I've always used:

using (StreamReader reader = new StreamReader(new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
{
}

According to MSDN, File.OpenRead is the same as:

new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read)

(the difference being FileShare of Read vs ReadWrite)


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜