Delete files in temp folder in C#

11,663

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);
        }
Share:
11,663
Nej Marinković
Author by

Nej Marinković

Updated on June 28, 2022

Comments

  • Nej Marinković
    Nej Marinković almost 2 years

    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.

    • Andrey
      Andrey over 8 years
    • Nej Marinković
      Nej Marinković over 8 years
      Thanks, but what I am actually trying to do is to delete ALL files in certain folder, regardless on their extension.
    • Andrey
      Andrey over 8 years
      use ''.'' as file name
    • T.S.
      T.S. over 8 years
      Why are you not using .net framework? System.IO.DirectoryInfo
    • Nej Marinković
      Nej Marinković over 8 years
      What does "." stands for? How do i define a folder in which i want to delete these files.
    • Nej Marinković
      Nej Marinković over 8 years
      @T.S. what is a framework? I think i am using 4.6 framework
    • Andrey
      Andrey over 8 years
      should be "*.*", I can't write it.
    • Nej Marinković
      Nej Marinković over 8 years
      @Andrey so basically asterisk is a folder, asterics is a file located in this folder?
    • Andrey
      Andrey over 8 years
      asterics is mask, folder is dot.
    • Andrey
      Andrey over 8 years
      "*.*" means all files. I find a way to write it as it should be.
    • T.S.
      T.S. over 8 years
      "what is a framework?" - why are you even asking questions here... not sure... I just gave you answer how to delete directory - go grab it
    • Thomas Ayoub
      Thomas Ayoub over 8 years