-4

I am having a problem in C# when trying to delete the directory (C:\Users\Terry\AppData\Local\Temp).

This is my current code:

private void Button1_Click(object sender, EventArgs e)
{
    var dir = new DirectoryInfo("C:\Users\"+ System.Environment.MachineName + "\AppData\Local\Temp");
    foreach (var file in Directory.GetFiles(dir.ToString()))
    {
        File.Delete(file);
    }
}

This code doesn't work for me. I'm fairly new to C# and I'm not familiar with deleting directories. Anybody able to help?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • 1
    This is utterly lazy. Obviously you haven't read the documentation, but you haven't even read what you have written. What do you think `File.Delete` does? – Maciej Jureczko Oct 01 '17 at 19:01
  • 1
    Seems like there should be a method or two in NET to get those folder names for us. – Ňɏssa Pøngjǣrdenlarp Oct 01 '17 at 19:23
  • `Path.GetTempPath()` will give you that exact path you are after. Also worth looking at `Environment.GetSpecialFolderPath()` to get other special folders. But if you want to delete the directory and all its files/subfolders you should call `dir.Delete(true)`. If you're going to iterate the files it's better to use `di.EnumerateFiles()` since you already have a `DirectoryInfo`. Or at least use `di.FullName` instead of `ToString()` since there's a known issue with `ToString()` called on a `DirectoryInfo` object obtained via the `Parent` property where it only returns the name – pinkfloydx33 Oct 01 '17 at 19:49

2 Answers2

2

Using the File.Delete method tries to delete a file. You want the Directory.Delete method to delete a directory.

https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx

Also, if you are creating temporary files or directory it is much better to use Path.GetTempPath() method. This will work in all version of Windows and respect any environment variables the user has set.

https://msdn.microsoft.com/en-us/library/system.io.path.gettemppath(v=vs.110).aspx

Nick Williams
  • 1,237
  • 6
  • 19
  • 40
-1

I think you're looking for

string path = Path.Combine(@"C:\Users", Environment.UserName, @"AppData\Local\Temp" );
Directory.Delete(path, true);
Nik
  • 1,780
  • 1
  • 14
  • 23