Вопрос

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);
                }
            }
        }
Это было полезно?

Решение

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);

Другие советы

Your error message seems to show that you're missing a backslash:

Access to the path 'C:Users\User\Recent' is denied.

(after the C:)

I Use Permissions Time Machine v1.1 to restore default permissions and remove "Access is denied" message for folder or files or registry keys or windows services or wmi objects it's free and fast and easy

download it from amyd projects blog

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top