How to delete a folder and its contents using C# or VB.NET

The easiest way to delete a folder and all the files and folders inside is to use the Directory.Delete command and pass in a parameter.

Directory.Delete(@"<FOLDERNAME>",true);

What the folder won't do is delete the folder if there are write protected files in any of the folders so its time to use a function instead. The following function will delete all files and subfolders, if there are any protected files, it will unprotect them and delete them.

public static void DeleteFolder(string sStartFolder)
    {
    foreach(string sFolder in System.IO.Directory.GetDirectories(sStartFolder))
        DeleteFolder(sFolder);

    foreach(string sFile in System.IO.Directory.GetFiles(sStartFolder))
    {
        try
            {
                File.Delete(sFile);
            }
        catch(Exception oExc)
            {
                if(oExc is UnauthorizedAccessException)
                    {
                    File.SetAttributes(sFile, FileAttributes.Normal);
                    File.Delete(sFile);
                    }
                else
                    throw oExc;
            }
        }

        Directory.Delete(sStartFolder);
    }

Any files that may be open will cause an error so throw them up to the calling function. If you need the code in VB.NET, its below.

Public Shared Sub DeleteFolder(ByVal sStartFolder As String)
    For Each sFolder As String In System.IO.Directory.GetDirectories(sStartFolder)
        DeleteFolder(sFolder)
    Next

    For Each sFile As String In System.IO.Directory.GetFiles(sStartFolder)

        Try
            File.Delete(sFile)
        Catch oExc As Exception

            If TypeOf oExc Is UnauthorizedAccessException Then
                File.SetAttributes(sFile, FileAttributes.Normal)
                File.Delete(sFile)
            Else
                Throw oExc
            End If
    End Try
    Next

    Directory.Delete(sStartFolder)
End Sub

Tags - .NET   File

Last Modified : June 2023


About... / Contact.. / Cookie...