简体   繁体   English

如何从根文件夹删除文件夹

[英]how to delete folder from a root folder

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: 流程如下:

  1. user selects file from the system 用户从系统中选择文件
  2. user add description 用户添加描述
  3. 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: 这是我的uploadImage.cs页面代码:

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 首先在此页面中,检查是否在Image / Department文件夹下有文件夹,如果没有,则在该部门下创建文件夹并将其存储在其他部门中,如果已经在该部门下创建了该商店映像

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;
}

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: 我的departmentMaste.cs页面代码:

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? 我怎样才能做到这一点?

update your RowDeleting event. 更新您的RowDeleting事件。

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("Select * from Department_Master where id=" + id, con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);

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

            con.Close();


            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";
            }
            BindEmployeeDetails();
        }

For Pop-up message, 对于弹出消息,

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 + "');");
        }

    }

} }

just make sure "ConfirmationBox" method is right to raise confirm window. 只需确保“ ConfirmationBox”方法正确即可引发确认窗口。

To Delete images from Images Table, you should have reference of Department_Master Table. 要从Images表中删除图像,您应该参考Department_Master表。 like a Column named DepartmentID with foreign Key reference into Images table. 就像名为DepartmentID的列,其中外键引用进入Images表。 even whenever you insert records into Images table, also insert respective DepartmentID , once you are done all these stuff, you can run delete command on Images table as 即使将记录插入Images表中,也要插入相应的DepartmentID ,一旦完成所有这些操作,就可以在Images表上运行delete命令,如下所示:

 SqlCommand cmd = new SqlCommand("Delete from Images where DepartmentID="+id +"; delete from Department_Master where ID=" + id, con);

Add this code into aspx page 将此代码添加到aspx页面

<script type="text/javascript">
function ConfirmationBox(id)
{
    return confirm('Are you sure to delete department Id:'+ id +'?' );
}
</script>

Use GetFiles to get the files from directory and use GetParent to get directory from the image. 使用GetFiles从目录获取文件,并使用GetParent从映像获取目录。

string dir = Directory.GetParent(photoPathFromDB).FullName;
string[] files = Directory.GetFiles(dir);
 foreach(string file in files)
     //do stuff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM