How to: Insert Data in Documents Without Writing to Disk

You can insert data into an Office solution document in memory, so that data is not written to the hard disk. If you need to send a document to a user as a byte array using the HTTP protocol, you can use this feature to modify data directly in the byte array, instead of creating a temporary file in which to modify the data.

Applies to: The information in this topic applies to document-level projects for Word 2007 and Word 2010. For more information, see Features Available by Office Application and Project Type.

To insert data in a document

  1. Load the document into memory as a byte array.

    string name = @"C:\Documents\WordApplication3.doc";
    System.IO.FileStream fileStream = null;
    byte[] bytes = null;
        fileStream = new System.IO.FileStream(
            name, System.IO.FileMode.Open, System.IO.FileAccess.Read);
        bytes = new byte[(int)fileStream.Length];
        fileStream.Read(bytes, 0, (int)fileStream.Length);
        if (fileStream != null)
  2. Pass the byte array to the server-side object model instead of a file name, and then perform your data manipulation.

    ServerDocument sd1 = null;
        sd1 = new ServerDocument(bytes, name);
        // Your data manipulation code goes here. 
  3. Send the document to the end user and close the ServerDocument.

        // If you have a Word document, use the MIME string:
        Response.ContentType = "application/msword";
        // If you have an Excel workbook, use the MIME string:
        //Response.ContentType = "application/";
        Response.AddHeader("Content-disposition", "filename=" + name);
        if (sd1 != null)

This example requires:

  • An ASP.NET project that contains the example code. The project must have the following configuration:

    • It must have a reference to the Microsoft.VisualStudio.Tools.Applications.ServerDocument.dll assembly (if the project targets the .NET Framework 4) or the Microsoft.VisualStudio.Tools.Applications.ServerDocument.v10.0.dll assembly (if the project targets the .NET Framework 3.5).

    • The code file into which you copy the code example must have an Imports (in Visual Basic) or using (in C#) statement for the Microsoft.VisualStudio.Tools.Applications namespace.

  • A Microsoft Office Word document named WordApplication3.doc that has a data cache, and is located in the folder C:\Documents.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

© 2015 Microsoft