Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I have an application in which I have an upload image page where I upload images and store those images in different folders under image folder and its path in a database. The flow of that goes like this:

user selects file from the system
user add description
user selects department from the drop-down list and according to that selection the image is stored in a different department's folder.

this is my uploadImage.cs page code:

In this page first we check that we have folder under Image/Department folder or not if not than we create folder and store image under that department else if already create that store image under that department


C#
protected void btnSubmit_Click1(object sender, EventArgs e)
{
    con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["WebGallery"].ConnectionString;
    string Description = tbImageName.Text.Trim();
    string Priority = lblPriority.Text.Trim();
    //Get Filename from fileupload control
    string imgName = fileuploadimages.FileName.ToString();
    //sets the image path
    string imgPath = "Images/Departments/" + "" + ddlDepartment.SelectedValue + "/";
    bool IsExists = System.IO.Directory.Exists(Server.MapPath(imgPath));
    if (!IsExists)
        System.IO.Directory.CreateDirectory(Server.MapPath(imgPath));
    //then save it to the Folder
    fileuploadimages.SaveAs(Server.MapPath(imgPath + imgName));
    //Open the database connection
    con.Open();
    //Query to insert images name and Description into database
    SqlCommand cmd = new SqlCommand("insert into Images(ImageName, Description, Path, Priority) values (@ImageName, @Description, @Path, @Priority)", con);
    //Passing parameters to query
    cmd.Parameters.AddWithValue("@ImageName", imgName);
    cmd.Parameters.AddWithValue("@Description", Description);
    cmd.Parameters.AddWithValue("@Path", imgPath + imgName);
    cmd.Parameters.AddWithValue("@Priority", lblPriority.Text);
    cmd.ExecuteNonQuery();
    //Close dbconnection
    con.Close();
    tbImageName.Text = string.Empty;
}


SQL
In this page we create,edit,update and delete department. Now when user click on delete button i want to delete that folder so that all the image under that folder will also delete.

My departmentMaste.cs page code:



C#
protected void BindEmployeeDetails()
{
    con.Open();
    SqlCommand cmd = new SqlCommand("Select * from Department_Master", con);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    con.Close();
    if (ds.Tables[0].Rows.Count > 0)
    {
        gvDetails.DataSource = ds;
        gvDetails.DataBind();
    }
    else
    {
        ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
        gvDetails.DataSource = ds;
        gvDetails.DataBind();
        int columncount = gvDetails.Rows[0].Cells.Count;
        gvDetails.Rows[0].Cells.Clear();
        gvDetails.Rows[0].Cells.Add(new TableCell());
        gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
        gvDetails.Rows[0].Cells[0].Text = "No Records Found";
    }

}

protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
    gvDetails.EditIndex = e.NewEditIndex;
    BindEmployeeDetails();
}

protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    //int id = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
    string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
    TextBox txtDepartment = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDepartment");
    con.Open();
    SqlCommand cmd = new SqlCommand("update Department_Master set DepartmentName='" + txtDepartment.Text + "'where ID=" + id, con);
    cmd.ExecuteNonQuery();
    con.Close();
    lblresult.ForeColor = Color.Green;
    lblresult.Text = id + " Details Updated successfully";
    gvDetails.EditIndex = -1;
    BindEmployeeDetails();
}

protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gvDetails.EditIndex = -1;
    BindEmployeeDetails();
}

protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    //int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
    string id = gvDetails.DataKeys[e.RowIndex].Values["ID"].ToString();
    con.Open();
    SqlCommand cmd = new SqlCommand("delete from Department_Master where ID=" + id, con);
    int result = cmd.ExecuteNonQuery();
    con.Close();
    if (result == 1)
    {
        BindEmployeeDetails();
        lblresult.ForeColor = Color.Red;
        lblresult.Text = id + " details deleted successfully";
    }
}

protected void gvDetails_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //getting username from particular row
        string id = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "ID"));
        //identifying the control in gridview
        ImageButton lnkbtnresult = (ImageButton)e.Row.FindControl("imgbtnDelete");
        //raising javascript confirmationbox whenver user clicks on link button
        if (lnkbtnresult != null)
        {
            lnkbtnresult.Attributes.Add("onclick", "javascript:return ConfirmationBox('" + id + "')");
        }

    }
}

protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName.Equals("AddNew"))
    {

        TextBox txtDepartment = (TextBox)gvDetails.FooterRow.FindControl("txtDepartment");

        con.Open();
        SqlCommand cmd =
            new SqlCommand("insert into Department_Master values('" + txtDepartment.Text + "')", con);
        int result = cmd.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindEmployeeDetails();
            lblresult.ForeColor = Color.Green;
            lblresult.Text = txtDepartment.Text + " Details inserted successfully";
        }
        else
        {
            lblresult.ForeColor = Color.Red;
            lblresult.Text = txtDepartment.Text + " Details not inserted";
        }
    }
}


i hope i am clear to you guys

How can I do that?
Posted
Updated 1-Jul-13 4:24am
v2
Comments
bbirajdar 1-Jul-13 10:08am    
You need to write code for that.. Tell us what have you tried...

As I can understand from your explanation is that, you want to delete all the files inside a directory along with all the files inside that directory.

If above is correct; following can be the approach:
Get the server map path url and get the folder alone. then loop through the below code and delete the files

DirectoryInfo di = new DirectoryInfo(PhysicalDirectoryPath); 
FileInfo[] rgFiles = di.GetFiles("*.aspx"); //For specific extensions or user GetFiles() for all the files.
foreach(FileInfo fi in rgFiles) 
{ 
// Delete the files here 
}

Once all the files are deleted, delete the directory as well

di .Delete();
Label2.Text = "Directory deleted successfully!";  
Hope this will help you

~Amol
 
Share this answer
 
v2
Comments
amitesh1989 1-Jul-13 11:39am    
Delete the files here using system.io.file.delete()) or how to delete file amol
Amol_27101982, India 2-Jul-13 5:18am    
fi.delete(); //to delete a file inside foreach look
amitesh1989 1-Jul-13 11:46am    
and what i FileInfo[] rgFiles = di.GetFiles("*.aspx"); *.aspx here
Amol_27101982, India 2-Jul-13 5:20am    
Replace:
FileInfo[] rgFiles = di.GetFiles("*.aspx");
By:
FileInfo[] rgFiles = di.GetFiles(); //This will consider all the files available in that folder.
 
Share this answer
 
I think this will help you.....Modify code as per your need...:)


C#
FileInfo[] fileList;
        DirectoryInfo dir = new DirectoryInfo(Server.MapPath("Directory Path"));
        fileList = dir.GetFiles();
        for (int i = 0; i < fileList.Length; i++)
        {
            fileList[i].Delete();
        }
 
Share this answer
 
Finally i got my solution::
C#
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string id = gvDetails.DataKeys[e.RowIndex].Values["DepartmentID"].ToString();
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from Department_Master where DepartmentID=" + id, con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);

        DataTable dt = ds.Tables[0];
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            string imgPath = "Images/Departments/" + "" + dt.Rows[i]["DepartmentID"] + "/";
            bool IsExists = System.IO.Directory.Exists(Server.MapPath(imgPath));
            if (IsExists)
                System.IO.Directory.Delete(Server.MapPath(imgPath), true);
        }

        con.Close();


        con.Open();
        SqlCommand cmd1 = new SqlCommand("Delete from Images where DepartmentID=" + id + "; delete from Department_Master where DepartmentID=" + id, con);
        int result = cmd1.ExecuteNonQuery();
        con.Close();
        if (result == 1)
        {
            BindDetails();
            lblresult.ForeColor = Color.Red;
            lblresult.Text = id + " details deleted successfully";
        }
        BindDetails();
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900