This article says that you need to use resizable MemoryStreams when working with the OpenXML SDK, and the sample code works fine.
However, when I translate the sample C# code into F#, the document remains unchanged:
open System.IO
open DocumentFormat.OpenXml.Packaging
open DocumentFormat.OpenXml.Wordprocessing
[<EntryPoint>]
let Main args =
let byteArray = File.ReadAllBytes "Test.docx"
use mem = new MemoryStream()
mem.Write(byteArray, 0, (int)byteArray.Length)
let para = new Paragraph()
let run = new Run()
let text = new Text("Newly inserted paragraph")
run.InsertAt(text, 0) |> ignore
para.InsertAt(run, 0) |> ignore
use doc = WordprocessingDocument.Open(mem, true)
doc.MainDocumentPart.Document.Body.InsertAt(para, 0) |> ignore
// no change to the document
use fs = new FileStream("Test2.docx", System.IO.FileMode.Create)
mem.WriteTo(fs)
0
It works fine when I use WordprocessingDocument.Open("Test1.docx", true), but I want to use a MemoryStream. What am I doing wrong?
Changes you’re making to
docare not reflected in MemoryStreammemuntil you closedoc. Placingdoc.Close()as belowfixes the problem and you’ll get text
Newly inserted paragraphat the top of yourTest2.docx.Also your snippet is missing one required reference:
from
WindowsBase.dll.EDIT: as ildjarn pointed out the more F#-idiomatic would be the following refactoring: