Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 调用IHTMLDocument的成员';s脚本引发访问冲突异常_C#_Winforms_Mshtml_Ihtmldocument2 - Fatal编程技术网

C# 调用IHTMLDocument的成员';s脚本引发访问冲突异常

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

以下代码仅在作为ClickOnce应用程序发布并安装后才会引发访问冲突异常。如果从Visual Studio运行它,即使我处于发布模式,也不会发生错误:

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,它返回文档中脚本的集合。