Home > database >  OpenXml Dotx to Docx Word Found Unreadable Content
OpenXml Dotx to Docx Word Found Unreadable Content

Time:09-28

I am trying to write code to fill a template's content controls then save it as a new file.

I found this very helpful entry Word OpenXml Word Found Unreadable Content And used the code there.

I copied the code from that post as shown below

   public static MemoryStream ReadAllBytesToMemoryStream(string path)
    {
        byte[] buffer = File.ReadAllBytes(path);
        var destStream = new MemoryStream(buffer.Length);
        destStream.Write(buffer, 0, buffer.Length);
        destStream.Seek(0, SeekOrigin.Begin);
        return destStream;
    }

    public static void Generate()
    {

        using MemoryStream stream = ReadAllBytesToMemoryStream(@"c:\Templates\TemplateTest.dotx");

        using (WordprocessingDocument wpd = WordprocessingDocument.Open(stream, true))
        {
            wpd.ChangeDocumentType(WordprocessingDocumentType.Document);
        }

        File.WriteAllBytes(@"c:\Templates\TemplateTestOutput.docx", stream.GetBuffer());
        return;
    }

It successfully creates the file, but the problem is, whenever I open the new docx file, it gives the "Word Found Unreadable Content" error. The template I made isn't complex, it just has 3 content controls with regular text for labels. I also tried copying a regular docx with just some lines of text, same error.

Whenever I click ok, on the Word Found Unreadable Content error, it shows the document just fine. I'm not sure what I'm doing wrong, I'm not even editing anything at this point.

CodePudding user response:

Figured out a solution.

Instead of using File.WriteAllBytes

File.WriteAllBytes(@"C:\\Templates\TemplateTestOutput.docx", stream.GetBuffer());

I used the following code:

using (FileStream fileStream = new FileStream(@"C:\\Templates\TemplateTestOutput.docx", System.IO.FileMode.CreateNew))
{
 stream.WriteTo(fileStream);
}
  • Related