-3

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();
        }
Gianni Giordano
  • 143
  • 1
  • 2
  • 13
  • Before you go any further, please rename your controls. (`listbox1` is **not** a good naming convention). BTW nor is using an empty `catch {}` block – jbutler483 Jan 13 '15 at 11:19
  • Not related to your issue, but swallowing exceptions is bad practice. Add handling on your catch block – apomene Jan 13 '15 at 11:20
  • See [Read last line of text file](http://stackoverflow.com/questions/11625595/read-last-line-of-text-file) for a proper implementation. There's a lot wrong with your code. – CodeCaster Jan 13 '15 at 11:24
  • thanks for your valuable suggestions. I'm a novice. May I have a sample code please for to start right? Thanks again in advance. – Gianni Giordano Jan 13 '15 at 11:32
  • just for to be more clear, in my snippet, I would to try to select like SQL steatement, only the added line using 'LinecountStartPositionBUFF' and 'LinecountEndPosition'. – Gianni Giordano Jan 13 '15 at 11:51

1 Answers1

2

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.

BendEg
  • 20,098
  • 17
  • 57
  • 131