使用复选框从文件夹中删除所选文件

时间:2014-09-10 05:59:52

标签: c# asp.net

在这段代码中,每件事情都是正确的,但是, 我希望当我点击“删除所选文件”按钮时,它会使用我的GridView上显示的CheckBox删除所选文件,而不使用任何JavaScript,jquery和任何插件。 我不知道怎么做到这一点。 我正在使用ASP.Net和C#。

这是我的ASPX代码:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:Label ID="Label1" runat="server" Text="Full Name : " ForeColor="Black"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Required" ForeColor="Red" ControlToValidate="TextBox1">
    </asp:RequiredFieldValidator><br /><br />
    <asp:FileUpload ID="FileUpload1" runat="server" AllowMultiple="true" /><br /><br />
    <asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click"  style="margin-bottom:10px;" />
    <asp:Button ID="Button2" runat="server" Text="Delete Selected Files" CausesValidation="false" style="margin-left:10px; margin-bottom:10px;" onclick="Button2_Click" />
    <asp:Button ID="Button3" runat="server" Text="Delete All" CausesValidation="false" style="margin-left:10px; margin-bottom:10px;" onclick="Button3_Click" />
    <div style="width:50%; overflow:auto; float:left;">
    <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AutoGenerateColumns="False">
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="Text" HeaderText="Image Name" />
            <asp:ImageField DataImageUrlField="Value" HeaderText="Image" ControlStyle-Height="100" ControlStyle-Width="100" />
        </Columns>
    <EditRowStyle BackColor="#999999" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#E9E7E2" />
    <SortedAscendingHeaderStyle BackColor="#506C8C" />
    <SortedDescendingCellStyle BackColor="#FFFDF8" />
    <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
    </div>
</asp:Content>

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Collections.Generic;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    public void MsgBox(String MessageToDisplay)
    {
        Label lblForMsg = new Label();
        lblForMsg.Text = "<script language='javascript'>window.alert('" + MessageToDisplay + "')</script>";
        Page.Controls.Add(lblForMsg);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DateTime curr = DateTime.Now;
        DateTime INDIAN_ZONE = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(curr, "India Standard Time");

        if (FileUpload1.HasFile)
        {
            HttpFileCollection hfc = Request.Files;
            for (int i = 0; i < hfc.Count; i++)
            {
                HttpPostedFile hpf = hfc[i];
                if (hpf.ContentLength > 0)
                {
                    string time1 = INDIAN_ZONE.ToString("MM-dd-yyyy_hhmmss");
                    string directoryPath = Server.MapPath(string.Format("./upload/" + TextBox1.Text));
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }
                    else
                    {
                    }

                    string fileName = Path.GetFileName(hpf.FileName);
                    fileName = time1 + fileName;
                    string path = "./upload/" + TextBox1.Text + "/";
                    hpf.SaveAs(Server.MapPath(path) + fileName);
                }
            }

            //GridView1 Bind with attach file
            string[] filePaths = Directory.GetFiles(Server.MapPath("~/upload/" + TextBox1.Text + "/"));
            List<ListItem> files = new List<ListItem>();
            foreach (string filePath in filePaths)
            {
                string fileName1 = Path.GetFileName(filePath);
                files.Add(new ListItem(fileName1, "~/upload/" + TextBox1.Text + "/" + fileName1));
            }
            GridView1.DataSource = files;
            GridView1.DataBind();
        }
        else
        {
            string time1 = INDIAN_ZONE.ToString("MM-dd-yyyy_hhmmss");
            string directoryPath = Server.MapPath(string.Format("./upload/" + TextBox1.Text));
            if (!Directory.Exists(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
            else
            {
            }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        string[] filePaths = Directory.GetFiles(Server.MapPath("~/upload/" + TextBox1.Text + "/"));
        foreach (string filePath in filePaths)
        {
            File.Delete(filePath);
        }

        string[] filePaths1 = Directory.GetFiles(Server.MapPath("~/upload/" + TextBox1.Text + "/"));
        List<ListItem> files = new List<ListItem>();
        foreach (string filePath in filePaths1)
        {
            string fileName1 = Path.GetFileName(filePath);
            files.Add(new ListItem(fileName1, "~/upload/" + TextBox1.Text + "/" + fileName1));
        }
        GridView1.DataSource = files;
        GridView1.DataBind();

        MsgBox("Delete All Successfully");
    }
}

在这段代码中,每件事情都是正确的,但是, 我希望当我点击删除所选文件按钮时,它会使用CheckBox删除所选文件。 我不知道怎么做到这一点。 我正在使用ASP.Net和C#。

2 个答案:

答案 0 :(得分:0)

Button2_Click()中,浏览网格视图行并检查每个复选框的检查值。如果选中,则检索该行文本框中的文件名。将它存储在数组中。并最终使用此数组删除存储在数组

中的文件名的文件
 protected void Button2_Click(object sender, EventArgs e)
 {
     int nGridRowCount = GridView1.Rows.Count;
     string[] filenames = new string[nGridRowCount];
     int index=0;
     for (int nSelect = 0; nSelect < nGridRowCount; nSelect++)
     {
         GridViewRow row = GridView1.Rows[nSelect];
         if (((CheckBox)(row.Cells[0].Controls[1])).Checked)
         {
             filenames[index]=GridView1.DataKeys[nSelect]["Text"].ToString();
             // or you can do this, see which one works for you
             //filenames[index] = row.Cells[1].Text;
             index++;
         }
     }

    // Here will come the code to traverse
    // the filenames array and delete the files using file names stored in it
}

答案 1 :(得分:0)

我得到了解决方案。

protected void Button2_Click(object sender, EventArgs e)
{
    foreach (GridViewRow di in GridView1.Rows)
    {
        CheckBox chkId = (CheckBox)di.FindControl("CheckBox1");
        if (chkId != null)
        {
            if (chkId.Checked)
            {
                string fileName = di.Cells[1].Text;
                File.Delete(Server.MapPath("~/upload/" + TextBox1.Text + "/" + fileName));
            }
        }
    }
}