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

The code below writes to a text file in a while loop, and sometimes it causes an error saying that "the process cannot access the file because it is being used by another process", etc. ". Typically, an error occurs when using (FileStream fs = File.OpenRead (filePath)). Is there a way to verify that the file is no longer in use or a way to properly dispose of the text writer?

 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();
                    }
+3
source share
4 answers

I have 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 is that FileShare Read vs ReadWrite)

+4

, , , , .

sud.Close() using(FileStream fs = File.OpenRead(filePath)) , , . .

, .

0

. - ? , , Dispose?

I also suggest you use consistently using. There are several places where you did not do this, and an exception may result in your file not being deleted correctly.

0
source

Source: https://habr.com/ru/post/1759694/


All Articles