Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete files but not folder C#

Tags:

c#

file

I have a code to delete folder and all files in it. I need to delete only files inside folder and not folder itself folder "1" for example must remain)... How can this be done using this code?

public class Deletefolder
    {
        public static void Main()
        {

           var dir = new DirectoryInfo(@"C:\d\wid\1");
            dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;

                dir.Delete(true);

            }

        }
like image 616
Raven111 Avatar asked Aug 29 '16 23:08

Raven111


1 Answers

You could use following code:

System.IO.DirectoryInfo di = new DirectoryInfo("YourPath");

foreach (FileInfo file in di.GetFiles())
{
    file.Delete(); 
}

Directly 'stolen' from this answer: https://stackoverflow.com/a/1288747/1661209

I think this question is almost an exact duplicate of that one.

like image 141
Max Avatar answered Oct 23 '22 02:10

Max