Introduction:

Here I will explain how to delete all files in folders and subfolders in asp.net using C# and VB.NET.


To delete files in folders and subfolders first we need to add namespace using System.IO

Once we add namespace need to write the code like as shown below


C# Code

// Delete direcoty or folder
protected void btnDelete_Click(object sender, EventArgs e)
{
string strpath = @"D:\" + txtdltName.Text;
if (Directory.Exists(strpath))
{
RemoveDirectories(strpath);
}
}
private void RemoveDirectories(string strpath)
{
//This condition is used to delete all files from the Directory
foreach (string file in Directory.GetFiles(strpath))
{
File.Delete(file);
}
//This condition is used to check all child Directories and delete files
foreach (string subfolder in Directory.GetDirectories(strpath))
{
RemoveDirectories(subfolder);
}
Directory.Delete(strpath);
}
 
 
 
VB.NET Code

  Delete direcoty or folder
Protected Sub btnDelete_Click(sender As Object, e As EventArgs)
Dim strpath As String = "D:\" + txtdltName.Text
If Directory.Exists(strpath) Then
RemoveDirectories(strpath)
End If
End Sub
Private Sub RemoveDirectories(strpath As String)
'This condition is used to delete all files from the Directory
For Each file1 As String In Directory.GetFiles(strpath)
File.Delete(file1)
Next
'This condition is used to check all child Directories and delete files
For Each subfolder As String In Directory.GetDirectories(strpath)
RemoveDirectories(subfolder)
Next
Directory.Delete(strpath)
lblResult.Text = "Directory deleted"
End Sub

0 comments:

Post a Comment