Saturday, 21 January 2012

Code to delete a Folder,all the Sub Folders and also files inside Subfolders and the root folder and The Root Folder in .Net




Create a console application.Then in  code behind put this code and enjoy :)
---------------------------------------------------------------------------
Imports System.Configuration
Imports System.Data
Imports System.IO
Imports System.IO.FileStream


Module Module1
    Sub Main()

        Dim line As String = String.Empty
        Dim file As StreamReader = Nothing
        Dim content As String = String.Empty
        Dim strFileSize As String = ""
        Dim root As New DirectoryInfo(ConfigurationManager.AppSettings("DirURL"))
        Dim arFi As IO.FileInfo() = root.GetFiles()
        For Each f1 As FileInfo In arFi
            f1.Delete()
        Next
        childDirectories(root.GetDirectories())
        If root.GetDirectories.Count = 0 And root.GetFiles.Count = 0 Then
            root.Delete()
        End If

    End Sub

    Public Sub childDirectories(ByVal root As DirectoryInfo())
        For Each child As DirectoryInfo In root
            FindAndDeleteFiles(child)
            childDirectories(child.GetDirectories()) 'recursion
            If child.GetDirectories.Count = 0 And child.GetFiles.Count = 0 Then
                child.Delete()
            End If
        Next
    End Sub
    Public Sub FindAndDeleteFiles(ByVal dir As DirectoryInfo)
        Dim arFi As IO.FileInfo() = dir.GetFiles()
        For Each f1 As FileInfo In arFi
            f1.Delete()
        Next

    End Sub
End Module


---------------------------------------------------
Add a Configuration file to your solution,then  add appsettings under <configuration> section
------------------------------------------------------------

 <appSettings>
        <add key="DirUrl" value="give full path of the root folder you want to delete"/>
    </appSettings>

----------------------------------------
press F5  and get ur folders deleted.