Choose a location:
posted 8/24/2010 by Raghav Khunger
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:
Source: http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx
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 using System.IO; #endregion namespace Extensions { 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 recursively deleting all the folders with all the files in it.
So how will we use it?
Here is the code which shows its implementation:
#region Using Directives using System.IO; using Extensions; #endregion public class Example { public static void Main() { const string dummyPathToDelete = @"C:\DummyFolder"; var directory = new DirectoryInfo(dummyPathToDelete); directory.DeleteAllFoldersAndFiles(); } }
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;
directory.DeleteAllFoldersAndFiles();
Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net? 18