1

I am trying to delete something from my local app data, this is my code

string folder = "%LOCALAPPDATA%\\test";
Directory.Delete(folder);

The error I get is that it's trying to find The %LOCALAPPDATA% Path inside of where my project is stored, I'm not sure if I'm doing anything wrong. If you can please help!

xkazi
  • 11
  • 2
  • 5
    You need to explicitly [expand environment variables](https://learn.microsoft.com/en-us/dotnet/api/system.environment.expandenvironmentvariables?view=net-5.0). Neither a plain string or any file managing function interprets them, unless otherwise noted. – Alejandro Jun 18 '21 at 21:39
  • note that `"%LOCALAPPDATA%\\\test` doesn't refer to the folder test but `tab` followed by `est`. You should use verbatim string instead: `@"%LOCALAPPDATA%\test"` – phuclv Jun 19 '21 at 04:41
  • 2
    Does this answer your question? [C# getting the path of %AppData%](https://stackoverflow.com/questions/867485/c-sharp-getting-the-path-of-appdata) – Matt U Jun 19 '21 at 04:47

1 Answers1

0

You can use Environment.GetFolderPath to retrieve the location of the LocalAppData folder. Example:

var localAppData = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var testFolder = System.IO.Path.Combine(localAppData, "test");
KristoferA
  • 12,287
  • 1
  • 40
  • 62
  • Ok but what if I want to delete the directory that is inside of the localappdata "test" too – xkazi Jun 19 '21 at 19:47
  • Then `Directory.Delete(testFolder);`. – Etienne de Martel Jun 19 '21 at 19:56
  • This is the error I get when I do that : This exception was originally thrown at this call stack: System.IO.__Error.WinIOError(int, string) System.IO.Directory.DeleteHelper(string, string, bool, bool, ref Microsoft.Win32.Win32Native.WIN32_FIND_DATA) System.IO.Directory.Delete(string, string, bool, bool) System.IO.Directory.Delete(string) File_Cleaner.Program.Main(string[]) in Program.cs – xkazi Jun 19 '21 at 21:12
  • Is the directory empty? `Delete` only works with empty directories, if it isn't, you'll have to use the second overload and make it recursive: `Directory.Delete(testFolder, true)`. – Etienne de Martel Jun 20 '21 at 01:39
  • Ah yes okay that works, thank you so much! – xkazi Jun 20 '21 at 04:08