Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;      
}
like image 395
Masoomian Avatar asked Nov 05 '12 07:11

Masoomian


1 Answers

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.

like image 160
Anders Arpi Avatar answered Oct 16 '22 00:10

Anders Arpi