HI WELCOME TO KANSIRIS

DELETE ALL FILES AND SUBDIRECTORIES FROM DIRECTORY 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 i.e sub folders in this folder. Also place some files and folders in sub folders. Now we want to delete all the files and folders placed in this folder and its sub folders.

A Directory that contains files or folders cannot be deleted so we first need to deletes all the child directories and also all the files in the directory and child directories.


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 sub directories 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())
        {
            file.Delete();
        }

        foreach (DirectoryInfo subdirectory in directory.GetDirectories())
        {
            EmptyFolder(subdirectory);
            subdirectory.Delete();
        }
    }

0 comments:

Post a Comment

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