Raven111
Raven111

Reputation: 81

Delete files but not folder C#

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);

            }

        }

Upvotes: 8

Views: 11196

Answers (1)

Max
Max

Reputation: 13338

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.

Upvotes: 12

Related Questions