4

I am working in Visual Studio 2015 and I am using C#. So I created Windows Form and I added a button named "button1". What I am trying to do is: when user clicks a button, the content of folder, named ( let´s say ) temp, located in C:/temp, is deleted, but the temp folder still remains.

I have tried to use this:

 private void button1_Click(object sender, EventArgs e)
    {
        string strCmdText;
        strCmdText = "del /q/f/s %TEMP%\* ";
        System.Diagnostics.Process.Start("CMD.exe", strCmdText);
    }

But I was told that this method is useful so I didn't use it anymore. And it also kept throwing an exception: "Unrecognized escape sequence". I was also told I should use System.IO namespace, I also tried to look for tutorials but I didn't find them useful.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Nej Marinković
  • 43
  • 1
  • 2
  • 6

3 Answers3

4

If youre looking to delete all files within the temp folder i would do something like this

        var dir = new DirectoryInfo("c:\\temp");
        foreach (var file in Directory.GetFiles(dir.ToString()))
        {
            File.Delete(file);
        }

or, if you are looking to delete certain files or types use something like this

        foreach (var file in Directory.GetFiles("c:\\temp", "*.xml", SearchOption.AllDirectories))
        {
            File.Delete(file);
        }
Simon Price
  • 3,011
  • 3
  • 34
  • 98
1

string userName = Environment.UserName;

        var dir = new DirectoryInfo("C:\\Users\\"+userName+ "\\AppData\\Local\\Temp");
        var d = new DirectoryInfo("C:\\Windows\\Temp");
       foreach (var file in Directory.GetFiles(d.ToString()))
        {
            File.Delete(file);
        }
0

Btw it says Unrecognized Escape Sequence cause you had a slash the wrong way around. This is how it should be:

string strCmdText;
            strCmdText = "del /q/f/s %TEMP%/* ";
            System.Diagnostics.Process.Start("CMD.exe", strCmdText);