Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

c# - Catching COMException specific Error Code

I'm hoping someone can help me. I've got a specific Exception from COM that I need to catch and then attempt to do something else, all others should be ignored. My error message with the Exception is:

System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'C:est.xls'. There are several possible reasons:

So my initial attempt was

try
{
 // something
}
catch (COMException ce)
{
   if (ce.ErrorCode == 0x800A03EC)
   {
      // try something else 
   }
}

However then I read a compiler warning:

Warning 22 Comparison to integral constant is useless; the constant is outside the range of type 'int' .....ExcelReader.cs 629 21

Now I know the 0x800A03EC is the HResult and I've just looked on MSDN and read:

HRESULT is a 32-bit value, divided into three different fields: a severity code, a facility code, and an error code. The severity code indicates whether the return value represents information, warning, or error. The facility code identifies the area of the system responsible for the error.

So my ultimate question, is how do I ensure that I trap that specific exception? Or how do I get the error code from the HResult?

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ErrorCode should be an unsigned integer; you can perform the comparison as follows:

try {
    // something
} catch (COMException ce) {
    if ((uint)ce.ErrorCode == 0x800A03EC) {
        // try something else 
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...