Deleting Document/Node from Umbraco

January 21, 2010

Deleting nodes from Umbraco is a simple task, but there appears is a lack of clear examples on the web. So here is a code snippet to help you get started.

if(doc.Published)
{
    doc.UnPublish();
    library.UnPublishSingleNode(doc.Id);
}

doc.delete();

So what’s going on here?

First of all we retrieve the document by instantiating the Document class with the node id. In this case 1234.

Now check to see if the document is published. If the document is published then call the UnPublishSingleNode method (passing the id of the document). This method removes the document from the runtime xml index (effectively removing it from the site).

Finally we call the delete method on the document. This moves the document into the trash (including all its children).

If you want to permanently delete the document then simply call the delete method again.  The document will then be entirely removed from Umbraco.

What about  umbraco.library.RefreshContent();

Some examples I found say that you need to call:

umbraco.library.RefreshContent();

In my example this is replaced with:

library.UnPublishSingleNode(doc.Id);

This is a more efficient method as RefreshContent() re-generates the entire runtime xml index, whereas UnPublushSingleNode() only affects the Document you are deleting (it also means you can check to see if the document is published first in order to prevent unnecessary work).

Advertisements

5 Responses to “Deleting Document/Node from Umbraco”

  1. kipusoep Says:

    Nice post.

    I allways used the RefreshContent() method, but your approach is much better! 🙂

  2. Razvan Says:

    Thanks. This works like a charm.

  3. Ogmios Says:

    library.UnPublishSingleNode(doc.Id);
    “Note, prior to this the Document should be marked unpublished by setting the publish property on the document object to false”

    therefore proper construction is:

    if (doc.Published)
    {
    doc.UnPublish();
    library.UnPublishSingleNode(doc.Id);
    }

  4. Peter Says:

    Thank you very much for sharing your insight and for helping people to get through faster.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: