Click here to Skip to main content
15,900,477 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
Hi all,

Create a file watcher where I want to read the last line of the file when content is changes. Did something line this.

C#
case WatcherChangeTypes.Changed:
	Console.WriteLine(string.Format("File {0} has been modified\r\n", e.FullPath));

    using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
    {
		using (StreamReader sr = new StreamReader(fs))
        {
            string line;
            while ((line = sr.ReadLine()) != null)
            {
                if (sr.EndOfStream)
                {
                    Console.WriteLine(line);
                }
            }
            sr.Close();
        }
        fs.Close();
    }

	break;


Stuck with two thing that I cannot find a solution. Each time when the content is changed the changed event fired twice.

The other thing is event the file read in shared mode when sometimes it gives the error that The process cannot access the file 'C:\test_file.txt' because it is being used by another process. How I test this was, register the file watcher, open the file in notepad add some content and save.

Any idea why this is really happen?
Posted

1 solution

OK, there are two parts to your question. First, the double-event is a normal occurance because of how the files are actually saved. Notepad is actually a problem application in this regards. You can find out more information about this and how to prevent it by going here:

http://stackoverflow.com/questions/449993/vb-net-filesystemwatcher-multiple-change-events[^]

As for the file being in use, that is because it is. :-) OK, sorry, I know that doesn't solve your problem. I believe your issue is that you need to change your FileShare mode to ReadWrite. Here is a Stack Overflow question that addresses that:

http://stackoverflow.com/questions/4400517/how-can-i-read-a-file-even-when-getting-an-in-use-by-another-process-exception[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900