Stacker
Stacker

Reputation: 8237

Releasing StreamReader File for a sec

i have a streamReader which i use to keep watching a file for any new lines added, it goes like this :

while (true)
{
  try
  {
    line = sr.ReadLine();
    if (line == null)
    {
      break;
    }
    if (!string.IsNullOrWhiteSpace(line))
    {
      //Do Stuff
    }
    Thread.Sleep(2);
  }
}

now i want to release the file for a while every now and then ,

i can close sr for a sec or two and then reintilize it and use it again but i was wondering if there is a proper way for doing that..

Upvotes: 0

Views: 181

Answers (2)

Oded
Oded

Reputation: 498982

Use FileSystemWatcher to track changes to the file and only then open the file to check for the new lines.

You can use the last seek position to start the new seek from, so the whole file doesn't need to be re-read.

Upvotes: 2

sehe
sehe

Reputation: 392921

proper way for doing that?

Reopening, Seek() to the old position and continue work should be your best option. If you want other parties to be able to continue accessing the file, just specify proper flags for FileShare e.g. FileShare.ReadWrite

Perhaps look at memory mapped files for .NET 4.0

Upvotes: 0

Related Questions