如何在不同的IOExceptions之间以编程方式区分?

我正在为写入Process对象的StandardInput流的代码执行一些exception处理。 进程有点像unix head命令; 它只读取部分输入流。 当进程终止时,写入线程失败:

IOException The pipe has been ended. (Exception from HRESULT: 0x8007006D) 

我想捕获这个exception,让它优雅地失败,因为这是预期的行为。 但是,对我而言,如何将其与其他IOExceptions进行强有力的区分并不明显。 我可以使用消息,但我理解这些是本地化的,因此这可能不适用于所有平台。 我也可以使用HRESULT,但我找不到任何指定此HRESULT仅适用于此特定错误的文档。 这样做的最佳方式是什么?

使用Marshal.GetHRForException()来检测IOException的错误代码。 一些示例代码可以帮助您对抗编译器:

 using System; using System.IO; using System.Runtime.InteropServices; class Program { static void Main(string[] args) { try { throw new IOException("test", unchecked((int)0x8007006d)); } catch (IOException ex) { if (Marshal.GetHRForException(ex) != unchecked((int)0x8007006d)) throw; } } } 

这可以通过添加特定类型的catch块来实现。 确保您级联它们,以便您的基本exception类型IOException将最后捕获。

 try { //your code here } catch (PipeException e) { //swallow this however you like } catch (IOException e) { //handle generic IOExceptions here } finally { //cleanup }