This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Programming
.NET 1.1+

Adding Files to My Recent Documents

If an application provides the facility to use files, Windows users expect to see recently loaded items in the My Recent Documents section of their Start menu. This functionality is missing from the .NET framework so the Windows API is used.

Referencing the API Function

The function that is required to add files to the My Recent Documents list, or to the Recent Items list in Microsoft Vista, is found in the Windows Application Programming Interface (API). There are several areas of API available to the .NET developer. The API required for this task is Shell32 and the function is SHAddToRecentDocs.

NB: A technical definition of the SHAddToRecentDocs function can be on the Microsoft web site.

The first thing that we need to do is reference the InteropServices namespace. This namespace provides the functionality required to access the required Windows API. Add the following using directive:

using System.Runtime.InteropServices;

With the link to the InteropServices defined, we can create a reference to the API function. This reference appears as a static function within a class.

static extern void SHAddToRecentDocs(int flags, string file);

The SHAddToRecentDocs function accepts two parameters. The flags parameter describes how the function is being used. The file parameter provides the detail of the file that is to be added to the list of recently opened documents. The function returns no value.

The flags parameter can accept one of two values. These are the named constants, SHARD_PATH and SHARD_PIDL. SHARD_PATH indicates that the file parameter holds a simple string containing the file path and name. This is the variant of the function we will use.

const int SHARD_PATH = 2;

Calling SHAddToRecentDocs

We can now call SHAddToRecentDocs from the class like any other function. The following demonstrates this by adding the file "c:\test.txt" to the My Recent Documents list. To test this, create the file "test.txt" in the root of the C: drive. Ensure that this file is not listed in the recent documents list before executing the code.

SHAddToRecentDocs(SHARD_PATH, @"C:\test.txt");


There are limitations to the use of SHAddToRecentDocs. Firstly, Windows must recognise the file type extension of the file being listed. I explain how to register a file type in the article, Programmatically Checking and Setting File Types. The second limitation is that you cannot add executable files (.exe) to the recent documents list.

12 August 2006