How to create Microsoft.Office.Interop.Word.Document object from byte array, without saving it to disk?

Masoomian picture Masoomian · Nov 5, 2012 · Viewed 11.9k times · Source

How can I create a Microsoft.Office.Interop.Word.Document object from byte array, without saving it to disk using 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;      
}

Answer

Anders Arpi picture Anders Arpi · Nov 5, 2012

There is no straight-forward way of doing this as far as I know. The Word interop libs are not able to read from a byte stream. Unless you are working with huge (or a huge amount of) files, I would recommend simply using a tmp file:

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);

I know this isn't the answer you're looking for, but in a case like this (where doing what you really want to do requires quite a bit of time and fidgeting) it might be worth considering whether or not development time outweighs runtime performance.

If you still want to look into a way to solve it the way you intend it to, I'd recommend the answers in this thread.