HI WELCOME TO KANSIRIS

DELETE SPECIFIC TYPE OF FILES FROM FOLDER AND SUBFOLDERS RECURSIVELY IN ASP.NET C#

Leave a Comment
Implementation: Let’s create an example to demonstrate the concept.

 Create a folder/directory with name “MyContents” in root directory. Add some files and folders in this folder. Also place some files and folders in sub folders. Now let’s say we want to delete all “.jpg“ files from “MyContent” folders and its sub folders.

Asp.Net C# Section

HTML Source
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
    </div>
    </form>
</body>
</html>

Asp.Net C# code to delete all files and subdirectories from directory

In code behind file e.g. default.aspx.cs write the following:

First of all include following required namespace:
using System.IO;

Then write the code as:
protected void btnDelete_Click(object sender, EventArgs e)
    {
        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/MyContents/"));
        EmptyFolder(directory);
    }

private void EmptyFolder(DirectoryInfo directory)
    {
        foreach (FileInfo file in directory.GetFiles())
        {
            if (file.Extension.ToLower().Equals(".jpg"))
            {
                file.Delete();
            }
        }
        foreach (DirectoryInfo subdirectory in directory.GetDirectories())
        {
            EmptyFolder(subdirectory);           
        }
    }

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.