Search code examples
c#office-interopcomexceptiononenote

COMException when converting OneNote into HTML (but it works for PDF)


I am trying to convert a OneNote section into HTML and keep running into a persistent error. It's weird because the same code works if I convert to PDF. I'd appreciate help wit this one.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using OneNote = Microsoft.Office.Interop.OneNote;
using Office = Microsoft.Office.Core;

namespace trial
{
    class Class1
    {
        [STAThread]
        static int Main(string[] args)
        {
            String strXML;
            OneNote.Application onApplication = new OneNote.Application();
            onApplication.GetHierarchy(null,OneNote.HierarchyScope.hsPages, out strXML);

            XDocument doc = XDocument.Parse(strXML);
            XNamespace ns = doc.Root.Name.Namespace;

            foreach (var sectionNode in from node in doc.Descendants(ns+"Section") select node)
            {
                string id = sectionNode.Attribute("ID").Value;
                string path = "C:\\elixir.html";

                if (id == "some specific ID")
                {
                    //confirmed that it reaches this point

                    try
                    {
                        onApplication.Publish(id, path, OneNote.PublishFormat.pfHTML, ""); //PDF conversion Works! But HTML doesn't.
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }
            }
            return 0;
        }
    }
}

Here are my references. All "Embed Interop Types" settings have been set to False. References

Here is the exception message

A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in Microsoft.Office.Interop.OneNote.dll
Exception from HRESULT: 0x8004201A

I checked that this error is a "file already exists" error, but that's wrong. The destination file is definitely not present as program commences running.


Solution

  • Changing the extension from

    string path = "C:\\elixir.html"; 
    

    to

    string path = "C:\\elixir.htm";
    

    fixed it.