Sounds like this is a dynamically-created Word document.
Since you have the document in the form of a Document
object, you should be able to get its string of XML, then bytes, by doing this:
Microsoft.Office.Interop.Word.Document d = new Microsoft.Office.Interop.Word.Document();
// All of your building of the document was here
// The object must be updated with content
string docText = d.WordOpenXML; // this assumes content is here
byte[] bytes = Encoding.UTF8.GetBytes(docText);
I don't think that saving the object to the file system first is required, since you already have the object you have built all dynamically, in memory. It should just be a matter of accessing its WordOpenXML
.
If you were grabbing the file from the file system, it would look pretty much the same, except for how the document is opened first:
string sourceFilePath = @"C:\test.docx";
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
var document = wordApp.Documents.Open(sourceFilePath);
string docText = document.WordOpenXML;
byte[] bytes = Encoding.UTF8.GetBytes(docText);
If you ever want to download these bytes back into a document, you'd need to do this:
string documentPath = @"C:\test.docx"; // can be modified with dynamic paths, file name from database, etc.
byte[] contentBytes = null;
// … Fill contentBytes from the database, then...
// Create the Word document using the path
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(documentPath, true))
{
// This should get you the XML string...
string docText = System.Text.Encoding.UTF8.GetString(contentBytes);
// Then we write it out...
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
See How can I form a Word document using stream of bytes for more information.