“System.IO.IOException: The operation completed successfully” exception

家住魔仙堡 提交于 2021-02-05 06:10:59

问题


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!


回答1:


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)




回答2:


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);
    }
}



回答3:


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.



来源:https://stackoverflow.com/questions/22106446/system-io-ioexception-the-operation-completed-successfully-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!