-5

As per solution posted in following post I have created form to read log files

BackgroundWorker & Timer, reading only new lines of a log file?

However I am getting file in use exception when writing log entries.

help

Community
  • 1
  • 1
Nitin Sawant
  • 7,278
  • 9
  • 52
  • 98
  • _"help"_ - is that your question? Can you perhaps show that you understand the problem, that you know _something_ about how opening, locking, reading and writing files works, that you have pinpointed the problem to a reproducible testcase, or do you just want the damn code fixed? – CodeCaster Jun 19 '13 at 12:43
  • Do you mean "when reading" log entries? – DonBoitnott Jun 19 '13 at 12:43
  • @Nitin you need to properly dispose the streamReader or fileStream. – Praveen Jun 19 '13 at 12:44

2 Answers2

1

You need to make sure that your log reading code opens the file in ReadWrite mode. See the excellent answer to this other post for a full explanation: How do I open an already opened file with a .net StreamReader?

Community
  • 1
  • 1
Clafou
  • 15,250
  • 7
  • 58
  • 89
1

When I do such file access/manipulation I usually take care of two things.

First, for reading I use the following code (see FileShare enumeration):

using (Stream s = File.Open(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)) { ... }

Second, I usually write a while loop for opening the file for reading/writing like this (draft code):

int tries=0;
while (tries < 10) {
    try {
        // try to open file for your operation
        break;
    } catch (IOException) {
        tries++;
        Thread.Sleep(200);
    }
}

EDIT: Accidently I used FileShare.Read first time in my answer instead of the more appropriate FileShare.ReadWrite. Now I've corrected it.

Zoltán Tamási
  • 12,249
  • 8
  • 65
  • 93
  • It is actually possible for a file to be concurrently written to and read. As demonstrated by [tail](http://en.wikipedia.org/wiki/Tail_(Unix)) for viewing logs as they are being written, which seems to be what the OP is trying to replicate. – Clafou Jun 19 '13 at 12:52
  • I just tried to give some general ideas. – Zoltán Tamási Jun 19 '13 at 12:54