Word API:防止文件转换

发布于 2024-09-09 02:56:15 字数 212 浏览 0 评论 0原文

我正在使用 Microsoft.Office.Interop.Word 命名空间中的 Documents.Open 方法打开 Word 文档。这工作正常,除了当我打开一个不是 Word 文档的文件时,它会自动转换为 Word 文档。我想找到一种方法来引发文档不是 Word 文档的异常,在打开文档之前检测文档是否是 Word 文档,或者检测文档在打开后是否已转换打开并转换。有人对如何实现这一目标有任何想法吗?

I'm opening word documents with the Documents.Open method in the Microsoft.Office.Interop.Word Namespace. This works fine, except that when I open a file that isn't a word document, it's automatically converted to be a word document. I'd like to find a way to either raise an exception of the document isn't a word document, detect if the document is, or is not, a word document before opening it, or detect if the document was converted after it is opened and converted. Does anyone have any ideas about how to accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

各自安好 2024-09-16 02:56:15

一个简单的测试是在尝试使用 Word 打开文档之前检查文档文件头中的幻数。

二进制 Word 文档 (.doc) 是复合文档,以 0xcfd0 开头,而 OpenXML 文档 (.docx) 以字符串“PK”开头。

static bool HasComoundDocumentSignature(string filename)
{
    using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
    {
        UInt16 magicNumber = br.ReadUInt16();      
        return magicNumber == 0xcfd0;
    }
}

static bool HasZipSignature(string filename)
{
    using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
    {
        UInt16 magicNumber = br.ReadUInt16();  
        return magicNumber == 0x4b50;
    }
}

static bool HasWordSignature(string filename)
{
    return HasCompoundDocumentSignature(filename) 
        || HasZipSignature(filename); 
}

A simple test would be to check for the magic number in the file header of the document before trying to open the document with Word.

Binary Word documents (.doc) are compound documents and start with 0xcfd0, where as OpenXML documents (.docx) start with the string "PK".

static bool HasComoundDocumentSignature(string filename)
{
    using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
    {
        UInt16 magicNumber = br.ReadUInt16();      
        return magicNumber == 0xcfd0;
    }
}

static bool HasZipSignature(string filename)
{
    using (BinaryReader br = new BinaryReader(File.Open(filename, FileMode.Open)))
    {
        UInt16 magicNumber = br.ReadUInt16();  
        return magicNumber == 0x4b50;
    }
}

static bool HasWordSignature(string filename)
{
    return HasCompoundDocumentSignature(filename) 
        || HasZipSignature(filename); 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文