0

I am building an windows software using c# to read log (textfile) that is continuously changing (every second )

Following is my code. When I run it how ever, i get an error

An exception of type 'System.IO.IOException' occurred in mscorlib.dll but was not handled in user code.

Additional information: The process cannot access the file 'C:\Users\Steve\Documents\Visual Studio 2015\Projects\iosLogger\IosSysLogger\bin\Debug\syslog.txt' because it is being used by another process.

My logic behind is that i want to build an logger that read the text file everytime there is a change to it. But it seems like it only invokes and loops around ( it crashes anyway) What would my problem be?

 string currentPath = System.Environment.CurrentDirectory;
    public Form1()
    {

        InitializeComponent();

        string currentPath = System.Environment.CurrentDirectory;


        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = currentPath;
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;


    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        textBox1.BeginInvoke(new Action(() =>
        {
            string[] fileContents;
            fileContents = File.ReadAllLines(currentPath + @"\syslog.txt");

            foreach (string line in fileContents)
            {
                textBox1.AppendText(line + "\n");
            }
        }));
    }
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Hyounmin Wang
  • 101
  • 2
  • 7
  • Assuming the process writing the file does not have a lock that prevents sharing, you can read the file by only requesting read permission when reading the file. See linked question. – Eric J. Jul 08 '15 at 14:08
  • please add `Thread.Sleep(50)` in `OnChanged` method,and the method will be called twice,you must skip once – Sky Fang Jul 08 '15 at 14:08
  • @EricJ. where is the link that you are refering to ? Thanks – Hyounmin Wang Jul 08 '15 at 14:38
  • It's at the top of your question now, as I marked this question as a duplicate. – Eric J. Jul 08 '15 at 14:40
  • @EricJ. Yes I am doing something very simillar to what you have mentioned but there is a sligt problem. It reads until it hits a null line and it crashes with the error i have mentioned. I think the error is bit different – Hyounmin Wang Jul 08 '15 at 14:44
  • Update your question (at the end of it... don't erase the original question) to show how you are now opening the file. File.`ReadAllLines()` will not open it with proper sharing. – Eric J. Jul 08 '15 at 22:44

0 Answers0