Monday, February 4, 2013

MS Word interop and {"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}

When you first see below exception your Word interop code execution in production environment, you think that there is something directly related with security. It normally results in spending more time on verifying the security of files and com dlls.

System.UnauthorizedAccessException {"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}

But is that the actual problem?
No.When we got this exception, we spent sometime on the security aspects. But when we looked at the below code we easily found that this is thrown because a com object is not supporting TextFrame property. The code was as follows.

For Each oShape As Word.Shape In wDoc.Shapes
                    If (oShape.TextFrame IsNot NothingThen
                        If (oShape.TextFrame.HasText <> 0 AndAlso oShape.TextFrame.TextRange IsNot NothingThen
                            'Processing code
                        End If
                    End If
...

Actually when we iterate through the Shapes, there may be some shapes which may not support the TextFrame property .We need to avoid those shapes from the TextFrame processing. This confusion would have been avoided if MSFT provides a meaningful exception message.

Happy debugging...

No comments: