你能告诉一个Word文档的byte[]数组是否是HTML吗?

本文关键字:byte 数组 是否是 HTML 文档 Word 一个 | 更新日期: 2023-09-27 18:13:17

我正在使用一个代码库,简而言之,它负责在基于web的查看器中显示文档,并为每个页码提供缩略图。加载策略和文档页数的计算根据文档类型进行分离,并将文档转换为通用格式进行表示。

我正在处理的问题涉及一些Word文档的初始页数计算。这些文档存储在第三方数据库中,其中包括文档的二进制流和扩展名(总是'doc')。为了计算文档的页数,我们使用Microsoft Office Interop如下所示:

    public int GetPageCount(byte[] file)
    {
        var filePath = Path.GetTempFileName();
        File.WriteAllBytes(filePath, file);
        return this.GetPageCount(filePath);
    }
    public int GetPageCount(string filePath)
    {
        try
        {
            this.OpenDocument(filePath);
            const WdStatistic statistic = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
            var pages = Document.ComputeStatistics(statistic, Type.Missing);
            return pages;
        }
        finally
        {
            //Closes handles, removes temp files, implementation omitted for brevity
            this.DisposeDocument();
            this.DisposeApplication();
        }
    }
    private void OpenDocument(string filePath)
    {
        // Create a new Microsoft Word application object
        this.Word = new Application();
        this.Word.Visible = false;
        this.Word.ScreenUpdating = false;
        object refFilePath = filePath;
        object html  = WdOpenFormat.wdOpenFormatWebPages;
        this.Document = this.Word.Documents.Open(ref refFilePath, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing, ref this.missing);
        if (Document == null)
        {
            throw new Exception(string.Format("Could not open Word document ({0})", filePath));
        }
    }

此代码处理的大多数文档都是正常的Word文档,可以正常工作。然而,其中一些文档实际上是保存为Word文档的HTML文档,不幸的是,使用wdstatisticpages的代码错误地推断出这些文档只有一个页面。我不确定这个现有的代码是否缺少一些东西,这些代码将使与互操作库的交互能够正确地确定HTML的页面数,这似乎是最简单的选择。

作为替代方案,我考虑是否有可能确定字节数组是否可以解析为HTML;我们有一个。html文件的渲染策略,但由于"doc"策略是从数据库中推断出来的,所以没有使用。将HTML文档的二进制文件转换成字符串,我们就得到了原始HTML,我想知道像正则表达式或一些第三方库这样聪明的东西是否可行。这两种方法我都没有问题,但我想知道。net中是否有一些优雅的东西可以做得更好。如果有。net原生的东西可用,最好不要引入依赖项或依赖正则表达式。比如:

    public bool IsHtml(byte[] file)
    {
        var fileString = Encoding.UTF8.GetString(file); 
        //Validate the fileString; how do we determine that the GetString() method correctly parsed and is not garbage?
        //return answer
    }

我应该指出,另一种选择是有第三方数据库的供应商改变他们的数据更正确,例如存储'html'作为其扩展名。但我内心好奇地想知道,处理代码中的差异是否真的可能,是否足够干净,值得考虑。我在StackOverflow上做了一些研究和搜索,但没有找到与此查询相关的任何内容。

谢谢你的帮助和想法。如果您需要更多的信息或细节,请询问。

你能告诉一个Word文档的byte[]数组是否是HTML吗?

理论上,您应该能够尝试使用XDocument.Load()的重载来尝试将文件加载到xml对象中,因为HTML是xml,假设它是有效的HTML。

实际上,大多数xml类都可以用来试图弄清楚这一点,特别是如果你已经有了字符串,你只需要假设无效的xml意味着它实际上是一个word文档。

编辑:废话,现在意识到新的文字格式也是XML,所以这可能不会工作....然而,我相信使用HtmlAgilityPack你可以使用类似的想法来解决这个问题

也看到这个线程的一些想法在各种第三方和。net技巧,可能是有帮助的->什么是最好的方式来解析html在c# ?