Relog can't open a binary log file if executed

2019-08-22 00:01发布

问题:

I've written a simple windows service to watch a folder and run relog (the windows tool to export data from binary perf mon files) on any files that arrive.

When I run it from my c# process (using System.Diagnostics.Process.Start()) I get:

Error:
Unable to open the specified log file.

But if I copy and paste the command into a console window it works fine.

I've looked all over the net but everything seems to point to a corrupt file, which I know is not the case as I can import perfectly when running manually.

Any help greatly appreciated.

回答1:

If you are using FileSystemWatcher to monitor for files it will fire the created event before the file is completely written to disk, this would cause the kind of error from relog about being unable to "open" a file since it might still be locked and technically corrupt as far as it's concerned.

I've written the following helper method that I always use in conjunction with FileSystemWatcher to wait for a file to be completely written and ready for processing after a created event and will also kick out after a timeout:

public static bool WaitForFileLock(string path, int timeInSeconds)
{
  bool fileReady = false;
  int num = 0;

  while (!fileReady)
  {
    if (!File.Exists(path))
    {
      return false;
    }

    try
    {
      using (File.OpenRead(path))
      {
        fileReady = true;
      }
    }
    catch (Exception)
    {          
      num++;
      if (num >= timeInSeconds)
      {
        fileReady = false;
      }
      else
      {
        Thread.Sleep(1000);
      }
    }
  }

  return fileReady;
}


标签: c# perfmon