开发者

Releasing StreamReader File for a sec

开发者 https://www.devze.com 2023-02-27 05:27 出处:网络
i have a streamReader which i use to keep watching a file for any new lines added, it goes like this :

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 rein开发者_StackOverflow社区tilize it and use it again but i was wondering if there is a proper way for doing that..


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消