C# 调用IHTMLDocument的成员';s脚本引发访问冲突异常
以下代码仅在作为ClickOnce应用程序发布并安装后才会引发访问冲突异常。如果从Visual Studio运行它,即使我处于发布模式,也不会发生错误:C# 调用IHTMLDocument的成员';s脚本引发访问冲突异常,c#,winforms,mshtml,ihtmldocument2,C#,Winforms,Mshtml,Ihtmldocument2,以下代码仅在作为ClickOnce应用程序发布并安装后才会引发访问冲突异常。如果从Visual Studio运行它,即使我处于发布模式,也不会发生错误: public static object InvokeScript(this IHTMLDocument2 document, string scriptName, object[] args = null) { FileLog.WriteLine("-------------------------------------- Will
public static object InvokeScript(this IHTMLDocument2 document, string scriptName, object[] args = null)
{
FileLog.WriteLine("-------------------------------------- Will invoke script --------------------------------------");
FileLog.WriteLine("document: " + document == null ? "NULL" : document.ToString());
FileLog.WriteLine("scriptName: " + scriptName);
FileLog.WriteLine("args: " + (args == null ? "NULL" : string.Join(", ", args.Select(a => a == null ? "NULL" : a.ToString()))));
FileLog.WriteLine("Stack: " + GetStack());
object result = null;
try
{
Type type = GetType(document);
result = Invoke(document, scriptName, args, result, type);
}
catch (Exception ex)
{
if (IsSecurityOrCriticalException(ex))
{
throw;
}
}
FileLog.WriteLine("-------------------------------------- Invoked script --------------------------------------");
return result;
}
private static object Invoke(IHTMLDocument2 document, string scriptName, object[] args, object result, Type type)
{
FileLog.WriteLine("Will Invoke");
result = type.InvokeMember(scriptName, System.Reflection.BindingFlags.InvokeMethod, null, ((IHTMLDocument)document).Script, args);
FileLog.WriteLine("Invoked");
return result;
}
private static Type GetType(IHTMLDocument2 document)
{
FileLog.WriteLine("Will get type");
Type type = (((IHTMLDocument)document).Script).GetType();
FileLog.WriteLine("Got type");
return type;
}
这是我试图实现的,但似乎我做错了什么。此外,脚本不会总是抛出异常。我已经测试了好几页,它们都很好,除了
异常只发生在Type Type=((IHTMLDocument)document.Script)中代码>行(最后记录的是“将获取类型”)
我试图运行的脚本是一个页面上还不存在的脚本(基本上是一个测试,看看脚本是否存在,如果不存在,那么我会将脚本注入页面)
你知道我做错了什么吗?你不应该更谨慎一点,检查文档是否不为null,是否可以转换为IHtmlDocument,然后调用Script,如果它也不为null,然后才调用GetType吗?避免使用像IHtmlDocument这样的古老界面。它可以追溯到石器时代,当时文档只有一个脚本。至少使用IHtmlDocument.scripts,它返回文档中脚本的集合。