Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load Word document from byte array

I have the whole MS Word file itself saved into a byte array.A want to load it the way I would if it was on file system but with the minimal use of Microsoft.Office.Interop.Word because it is very slow when it gets the the .Open(args[]) part.

like image 329
mathinvalidnik Avatar asked Aug 12 '13 10:08

mathinvalidnik


2 Answers

Try this....

      byte[] bte = File.ReadAllBytes("E:\\test.doc"); // Put the Reading file
        File.WriteAllBytes(@"E:\\test1.doc", bte); // Same contents you will get in byte[] and that will be save here 
like image 107
SAR Avatar answered Oct 12 '22 22:10

SAR


There is no supported way to do it right off-the-bat using Interop.Word, as there are no methods supporting byte arrays.

As a viable workaround you can use a temporary file in the following way:

// byte[] fileBytes = getFileBytesFromDB();
var tmpFile = Path.GetTempFileName();
File.WriteAllBytes(tmpFile, fileBytes);

Application app = new word.Application();
Document doc = app.Documents.Open(filePath);

// .. do your stuff here ...

doc.Close();
app.Quit();
byte[] newFileBytes = File.ReadAllBytes(tmpFile);
File.Delete(tmpFile);

Fore additional info, read this post on my blog.

like image 39
Darkseal Avatar answered Oct 12 '22 22:10

Darkseal