3

I'm getting this exception

System.IO.IOException: The operation completed successfully.

in the following chunk of code. This code runs in a windows service.

foreach (var error in _currentPowerShell.Streams.Error)
{
    if (!string.IsNullOrEmpty(error.FullyQualifiedErrorId))
    {
        if (!(error.CategoryInfo.Activity == "Get-Alias"))
            throw error.Exception;
    }
}

It doesn't make sense at all since I'm not doing any IO operation!

AccurateEstimate
  • 363
  • 2
  • 16

3 Answers3

2

I think I've seen that before, when using 'overlapped' streams. It's a terrible error message

It's an overlapped I/O (IOCP) completion status. The thrown exception is documented as "An I/O error has occurred." Its misleading that it is has the message "The operation completed successfully".

This also might happen when trying to access files that are zone restricted (like when downloaded from an internet zone from IE)

Iain Ballard
  • 4,433
  • 34
  • 39
0

Part of your problem diagnosing this error is probably a result of the way you handle the returned errors masking the actual exception location. Throwing the exception retrieved from the error directly wipes out the stack trace. Try wrapping the exception provided instead of throwing it directly to get better error information. Then check the stack trace to see where the error really happened.

Create a custom exception:

public class PSException : Exception
{
}

Then change your code to wrap the exception from the PowerShell error:

foreach (var error in _currentPowerShell.Streams.Error)
{
    if (!string.IsNullOrEmpty(error.FullyQualifiedErrorId))
    {
        if (!(error.CategoryInfo.Activity == "Get-Alias"))
            throw new PSException("An error occurred in the PowerShell instance.", error.Exception);
    }
}
JamieSee
  • 12,696
  • 2
  • 31
  • 47
0

From my understanding you are running PowerShell script within your own host (am I'm right?). In this case you can catch all exceptions which happen during Script execution in the same way, as you catch exceptions in C#. For this you just need to set in your script $ErrorActionPreference = "Stop".

Hope this will help you to get more information about the error you get. Also you can use this approach instead of reading the stream for errors. It's just reading streams and parsing them works very bad if you need your program to be localized.