Home > database >  How can i delete a directory in localappdata in the current user
How can i delete a directory in localappdata in the current user

Time:09-30

System.IO.DirectoryInfo di = new DirectoryInfo(@"C:\Users\%userprofile%\AppData\Local\MyFolder");

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
    dir.Delete(true); 
}

Im using this code to delete a directory in %localappdata% in the current used user. But it says that the folder does not exist. I cant figure how to write the path.

Thank you

CodePudding user response:

You can use the following code:

string path;
path = @"%LOCALAPPDATA%";
path = Environment.ExpandEnvironmentVariables(path);

You can refer to the following link for more details: https://docs.microsoft.com/en-us/dotnet/api/system.environment.expandenvironmentvariables?view=net-5.0

CodePudding user response:

The problem is that: "C:\Users\%userprofile%\AppData\Local\MyFolder" expands into "C:\Users\C:\Users\username\AppData\Local\MyFolder".

You should be doing "%userprofile%\AppData\Local\MyFolder".

This is where basic debugging skills like breakpoints and examining error messages can save you a lot of trouble. The debugger would no doubt be telling you which directory it says doesn't exist.

Even just copy pasting your intended path into Explorer reveals the problem.

CodePudding user response:

The solution was a windows 11 bug as you saw in the comments of the post I did it with this method How can i get the path of the current user's "Application Data" folder?

  • Related