How can I delete a OneNote page in C#?

305 Views Asked by At

I'm using the OneNote interop in C# to try and delete a page using the following block of code:

static string GetObjectId(string parentId, HierarchyScope scope, string objectName)
{
    string xml;
    onenote.GetHierarchy(parentId, scope, out xml);

    var doc = XDocument.Parse(xml);
    var nodeName = "";

    switch (scope)
    {
        case (HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
        case (HierarchyScope.hsPages): nodeName = "Page"; break;
        case (HierarchyScope.hsSections): nodeName = "Section"; break;
        default:
            return null;
    }

    var node = doc.Descendants(ns + nodeName)
        .Where(n => n.Attribute("name").Value == objectName)
        .FirstOrDefault();

    return node.Attribute("ID").Value;
}

static string DeletePage(string sectionId, string pageId, string pageName)
{
    var pageId = GetObjectId(sectionId, HierarchyScope.hsPages, pageName);
    onenote.DeleteHierarchy(pageId, DateTime.MinValue, true);
}

But each time I open OneNote the page remains.

I have been reading on the following page that this is the method I should be using however I don't appear to be having much luck: https://msdn.microsoft.com/en-us/library/office/gg649853(v=office.14).aspx

Can someone please point me in the right direction on how to delete a page in OneNote using the OneNote interop in C#.

1

There are 1 best solutions below

0
On BEST ANSWER

This is an old question but since there's no answer... I have found that simply calling the functions as follows:

onenote.DeleteHierarchy(pageId)

works and will result in the file being sent to the recycle bin. If you want to fully delete the page, do the following:

onenote.DeleteHierarchy(pageId, deletePermanently:true)

Using the dateExpectedLastModified parameter is a bit tricky.
Per MSDN– (Optional) The date and time that you think the object you want to delete was last modified. If you pass a non-zero value for this parameter, OneNote proceeds with the update only if the value you pass matches the actual date and time the object was last modified. Passing a value for this parameter helps prevent accidentally overwriting edits users made since the last time the object was modified.