Why am I getting a Unhandled Exception: System.IO.IOException when trying to read from a file being written to?

若如初见. 提交于 2019-12-04 14:39:13

lines = File.ReadAllLines(args[1] + "\Chat.log").Length;

There's your problem. That method opens the file, reads all the lines and closes it again. It uses "normal" file share settings when opening the file, FileShare.Read. That denies write access to any other process that also has the file opened.

That cannot work here, you've already have the file opened with write access. The 2nd process cannot deny it. The IOException is the result.

You cannot use File.ReadAllLines() as-is here, you need to open a FileStream with FileShare.ReadWrite, pass it to a StreamReader and read all lines.

Beware the very troublesome race potential you've got here, there's no guarantee that the last line you'll read is a complete line. Getting only a \r and not the \n at the end of the line is a particularly tricky issue. This will strike randomly and infrequently, the hardest bugs to troubleshoot. Maybe your Flush() call fixes it, I've never been brave enough to put this to the test.

Allowing the second program ReadWrite access on the file would work in this case.

//lines = File.ReadAllLines(args[1] + "\\Chat.log").Length;
//Commenting the above lines as this would again open a new filestream on the chat.log
//without the proper access mode required.


    using (FileStream fsReader = new FileStream(args[1] + "\\Chat.log", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using (StreamReader sr = new StreamReader(fsReader))
            {
                while (sr.ReadLine() != null)
                    lines++;
            }
        }
StreamReader sr = new StreamReader("f:\\watch\\input.txt");

input.txt might not be available for reading?

Also use the using statement instead of Close() in the 1st application (in case an exception is thrown).

Otherwise it is OK. The file share may require additional permissions though (can't really affect that).

I have missed one piece of code:

int newlines = File.ReadAllLines(path).Length;

use the stream with a StreamReader for that.

MSDN offers two ways to not obtain an exclusive hold:

A FileStream object will not have an exclusive hold on its handle when either the SafeFileHandle property is accessed to expose the handle or the FileStream object is given the SafeFileHandle property in its constructor.

The documentation implies that the inverse is true:

Opening a FileStream without setting the SafeFileHandle means the FileStream maintains an exclusive hold on the file handle (which is inline with the IO exception that is supposed to be thrown).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!