Search code examples
c#.netwinformsfilesystemwatcher

The process cannot access the file because it is being used by another process when I count


I've build a File System Watcher solution, and, I would to retrieve the changes made on log file, extracting only the added line, but I can not in this because I always error that the process cannot access the file because it is being used by another process. My code is this for retrieve the added line is this:

using (var file = new FileStream(FileName,
                                        FileMode.Open,
                                        FileAccess.Read,
                                        FileShare.Read))

        using (var sr = new StreamReader(file))
        {
                try
                {
                    Thread thread = new Thread(delegate()
                    {
                        listBox1.Invoke((MethodInvoker)(() =>
                        {

                            listBox1.Items.Clear();//this is the listbox that list every added line and that I clear before of to be filled
                            string[] lines = File.ReadLines(fileName)
                                                 .Skip(LinecountStartPositionBUFF)
                                                 .Take(LinecountEndPosition - LinecountStartPositionBUFF)
                                                 .ToArray();
                            listBox1.Items.AddRange(lines);

                        }));
                    });

                    thread.Start();

                    while (thread.IsAlive)
                        Application.DoEvents();
                }

                catch
                { }

            return sr.ReadLine();
        }

Solution

  • You can not open the file in a FileStream and later access it via File.ReadLines, because FileStream locks the file. I would change the complete code.