C# – Cannot create documents with Open XML SDK

cnetopenxmlopenxml-sdkvisual studio

I'm learning to use the Open XML SDK with Visual Studio Community 2015. I tried to create a document by following the example here: https://msdn.microsoft.com/en-us/library/dd440953(v=office.12).aspx

My code:

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
          Program p = new Program();
          p.HelloWorld("abc.docx");
        }

        public void HelloWorld(string docName)
        {
            // Create a Wordprocessing document. 
            using (WordprocessingDocument package = WordprocessingDocument.Create(docName, WordprocessingDocumentType.Document))
            {
                // Add a new main document part. 
                package.AddMainDocumentPart();

                // Create the Document DOM. 
                package.MainDocumentPart.Document =
                  new Document(
                    new Body(
                      new Paragraph(
                        new Run(
                          new Text("Hello World!")))));

                // Save changes to the main document part. 
                package.MainDocumentPart.Document.Save();
            }
        }

    }
}

I got an error on WordprocessingDocument.Create:

Error   CS0012  The type 'Package' is defined in an assembly that is not referenced. 
You must add a reference to assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=1234'.  
ConsoleApplication1 c:\users\john\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs

I've already installed the DocumentFormat.OpenXml package with nuget

What is wrong with the code?

Best Answer

The error message tells you already how to solve your issue:

You must add a reference to assembly 'WindowsBase, Version=4.0.0.0, Culture=neutral, PublicKeyToken=1234'.

Right-click the References node of your project in Visual Studio's Solution Explorer and choose Add Reference. Then, under Assemblies -> Framework you have to select WindowsBase and that as a reference. Then recompile your project (note that this requires that you are using .NET Framework 3.5 or any later version).