9

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;      
}
shA.t
  • 16,580
  • 5
  • 54
  • 111
Masoomian
  • 740
  • 1
  • 10
  • 25

1 Answers1

14

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.

Community
  • 1
  • 1
Anders Arpi
  • 8,277
  • 3
  • 33
  • 49
  • Hi, I am trying to do something similar, but at the line `var tmpFileStream = File.OpenWrite(tmpFile);` Visual Studio is giving an error saying "Overload resolution failed because no accessible 'File' accepts this number of arguments". Any idea why that is? – Art F Nov 15 '12 at 15:24
  • Use `System.IO.File.OpenWrite(...)` (with the fully qualified namespace). See this question for more info: http://stackoverflow.com/questions/8314628/using-a-html-file-for-mail-body-in-net-mail – Anders Arpi Nov 17 '12 at 14:15
  • 1
    Note that the temp file will stay on disk forever if you use the exact code in this example. If your system is converting a lot of files then consider creating the file with `FileOptions.DeleteOnClose`. See: https://stackoverflow.com/questions/3240968 – Adam Jun 14 '17 at 09:00