How to add to the Windows recent documents in C#

I realize that I haven’t written anything here for ages… so I looked through my old code for something simple but useful, and found this.

If ever you need to add a file to the Windows recent document list, this does the trick. I’m using this in a Windows Forms application that can open and view a number of file types, such as videos, audio and text files. Adding them to the recent documents allows me to open the files using the registered file handlers (I don’t register my application to handle the files on a system level) to compare my viewers to others. The code is simple and self-explanatory, so here it is without any explanation:

using System.Runtime.InteropServices;
using System.Security;

namespace Sample
    public static class Example
        public static void AddToRecentDocuments(string path)
            NativeMethods.SHAddToRecentDocs(ShellAddToRecentDocsFlags.Path, path);

    internal enum ShellAddToRecentDocsFlags
        Pidl = 0x001,
        Path = 0x002,

    internal static class NativeMethods
        // Note: The function call fails if we use CharSet.Unicode or CharSet.Auto or if path is not Ansi.
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "1"), DllImport("shell32.dll", CharSet = CharSet.Ansi)]
        public static extern void SHAddToRecentDocs(ShellAddToRecentDocsFlags flag, [MarshalAs(UnmanagedType.LPStr)] string path);

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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