Search code examples
c#directoryaccess-denieddelete-file

Access denied - Trying to delete all files in a folder


I'm currently trying to delete all files in a folder (Recently opened files), but without any luck, I get the message: "Access to the path 'C:\Users\User\Recent' is denied." . I've been looking around to see if there were any solutions, but unfortunately I can't find anything.

Image:

String recent = Environment.ExpandEnvironmentVariables("%USERPROFILE%") + "\\Recent";
                        EmptyFolderContents(recent);

    private void EmptyFolderContents(string folderName)
        {

            foreach (var Folder in Directory.GetDirectories(folderName))
            {
                try
                {
                    Directory.Delete(Folder, true);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

            foreach (var Files in Directory.GetFiles(folderName))
            {
                try
                {
                   File.Delete(Files);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex);
                }
            }
        }

Solution

  • The reason you are getting the Access Denied error is because you can't just delete files from that folder. They are virtual paths to real files. There is probably a better way to do what you are doing.

    Here is an alternative that I found here. It uses WinAPI, which is never fun, but it works.

    //you'll need to add this.
    using System.Runtime.InteropServices;
    
    [DllImport("shell32.dll")]
    public static extern void SHAddToRecentDocs(ShellAddToRecentDocsFlags flag, IntPtr pidl);
    
    public enum ShellAddToRecentDocsFlags
    {
        Pidl = 0x001,
        Path = 0x002,
    }
    
    //then call this from your method
    SHAddToRecentDocs(ShellAddToRecentDocsFlags.Pidl, IntPtr.Zero);