【问题标题】:How to create Microsoft.Office.Interop.Word.Document object from byte array, without saving it to disk?如何从字节数组创建 Microsoft.Office.Interop.Word.Document 对象,而不将其保存到磁盘?
【发布时间】:2012-11-05 07:34:51
【问题描述】:

如何从字节数组创建Microsoft.Office.Interop.Word.Document 对象,而不使用 C# 将其保存到磁盘?

public static int GetCounterOfCharacter(byte[] wordContent)
{
   Application objWord = new Application();
   Microsoft.Office.Interop.Word.Document objDoc = new Document();
   //objDoc = objWord.Documents.Open(("D:/Test.docx"); i want to create document from byte array "wordContent"
   return  objDoc.Characters.Count;      
}

【问题讨论】:

    标签: c# ms-word office-interop


    【解决方案1】:

    据我所知,没有直接的方法可以做到这一点。 Word 互操作库无法从字节流中读取。除非您正在处理大量(或大量)文件,否则我建议您只使用 tmp 文件:

    Application app = new Application();
    
    byte[] wordContent = GetBytesInSomeWay();
    
    var tmpFile = Path.GetTempFileName();
    var tmpFileStream = File.OpenWrite(tmpFile);
    tmpFileStream.Write(wordContent, 0, wordContent.Length);
    tmpFileStream.Close();
    
    app.Documents.Open(tmpFile);
    

    我知道这不是您要寻找的答案,但在这种情况下(做您真正想做的事情需要相当多的时间和坐立不安)可能值得考虑是否开发时间大于运行时性能。

    如果您仍想按照您的意愿寻找解决问题的方法,我建议您在this 线程中找到答案。

    【讨论】:

    • 嗨,我正在尝试做类似的事情,但是在var tmpFileStream = File.OpenWrite(tmpFile); 行,Visual Studio 给出了一个错误,提示“重载解析失败,因为没有可访问的'文件'接受这个数量的参数”。知道这是为什么吗?
    • 使用System.IO.File.OpenWrite(...)(带有完全限定的命名空间)。有关更多信息,请参阅此问题:stackoverflow.com/questions/8314628/…
    • 请注意,如果您使用此示例中的确切代码,临时文件将永远保留在磁盘上。如果您的系统正在转换大量文件,请考虑使用FileOptions.DeleteOnClose 创建文件。见:stackoverflow.com/questions/3240968
    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-09
    • 1970-01-01
    相关资源
    最近更新 更多