Yesterday, I saw a person posted a question on forums “How to delete all the files and folders inside a folder” with C#. I thought I should blog for it. So I made a sample project to demonstrate the same. I made a extension method which will delete all the files and folders inside a particular folder. Before going further you should read this:
What are Extension Methods?
Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.
Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework that is being introduced with .NET as part of the "Orcas" release.
Now come to the code. The class which contains the extension method:
#region Using Directives
public static class FileExtensions
public static void DeleteAllFoldersAndFiles(this DirectoryInfo directoryInfo)
foreach (FileInfo fileInfo in directoryInfo.GetFiles()) fileInfo.Delete();
foreach (DirectoryInfo childDirectories in directoryInfo.GetDirectories()) childDirectories.Delete(true);
Above in the first line of DeleteAllFoldersAndFiles method I am deleting all the files and in the second line I am recurs
So how will we use it?
Here is the code which shows its implementation:
#region Using Directives
public class Example
public static void Main()
const string dummyPathToDelete = @"C:\DummyFolder";
var directory = new DirectoryInfo(dummyPathToDelete);
Above I have used the hardcoded path dummyPathToDelete in my example, you can use your own logic to decide the path. Then I gave the reference of the class where my extension method resides and that’s it I am ready to use DeletAllFoldersAndFiles method with this code;
Do let me know your feedback, comments.
This is an off-topic post. I had to blog about it because Activision deserves to be slammed for not providing the pause option when playing "extinction" or "squad" offlin...
by: Vivek Thakur
How to add external files in Web Deployment Project Setup MSI using Visual Studio Web deployment pro
Error code 1603 with Visual Studio Web Deployment Project on Windows 7 While creating an MSI setup p
Assume you have a text file, and you want to read all its contents into a C# string variable. Here i
In this post, I'm going to quickly show you how to create a jQuery Mobile Registration / Signup login dialog box. If you've been following my posts so far, you should hav...
by: Tim Eisenhauer
What kind of email newsletter would you prefer to receive from CodeAsp.Net?