【原创】ASP.NET C# 获取指定目录文件的排序和删除

注意:本篇为博主原创,若要转载请注明出处,谢谢合作!

前台:

<%@ Page Title="" Language="C#" MasterPageFile="~/Admin/Include/Admin_Main.master"
    AutoEventWireup="true" CodeFile="c.aspx.cs" Inherits="Test_file_c" StylesheetTheme="Admin" %>

<asp:Content ID="Content1" ContentPlaceHolderID="contentPlaceHolder1" runat="Server">
    <yyc:SmartGridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="fullname"
        SkinID="AdminGridView" AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging"
        OnSorting="GridView1_Sorting" OnRowCommand="GridView1_RowCommand1">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="All" runat="server" Text="全选" />
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="Item" ToolTip='<%# Eval("fullname")%>' runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="文件名" SortExpression="name">
                <ItemTemplate>
                    <asp:HyperLink ID="url" runat="server" NavigateUrl='<%# Eval("url") %>' Target="_blank"
                        Text='<%# Eval("name") %>'></asp:HyperLink>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="文件大小" SortExpression="size">
                <ItemTemplate>
                    <asp:Label ID="size" runat="server" Text='<%# Bind("size") %>'></asp:Label><asp:Label
                        ID="kb" runat="server" Text='KB'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="文件类型" SortExpression="type">
                <ItemTemplate>
                    <asp:Label ID="type" runat="server" Text='<%# Bind("type") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="修改日期" SortExpression="date">
                <ItemTemplate>
                    <asp:Label ID="date" runat="server" Text='<%# Bind("date") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="操作">
                <ItemTemplate>
                    <asp:LinkButton ID="delete" runat="server" CommandName="Del" CommandArgument='<%# Eval("fullname") %>'
                        CausesValidation="false" OnClientClick="return confirm('确定要删除该文件吗?一旦删除将无法恢复!')">删除</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <CascadeCheckboxes>
            <yyc:CascadeCheckbox ChildCheckboxID="Item" ParentCheckboxID="All" />
        </CascadeCheckboxes>
        <CheckedRowCssClass CheckBoxID="Item" CssClass="SelectedRow" />
        <CustomPagerSettings PagingMode="Webabcd" TextFormat="每页{0}/{1}条记录 第{2}页/共{3}页 " />
        <PagerSettings FirstPageText="首页" LastPageText="末页" Mode="NextPreviousFirstLast"
            NextPageText="下一页" PreviousPageText="上一页" />
    </yyc:SmartGridView>
    <br />
    <br />
    <asp:Button ID="Del" runat="server" Text="删除" OnClick="Del_Click" />
    <asp:Label ID="ResultMsg3" runat="server" Text="Label"></asp:Label>
</asp:Content>


后台:

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public partial class Test_file_c : System.Web.UI.Page
{
    protected string dirPath = "~/UploadFiles/image/yuekan/";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            ViewState["sortexpression"] = "date";
            BindGridView(dirPath, ViewState["sortexpression"].ToString());
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        BindGridView(dirPath, ViewState["sortexpression"].ToString());
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["sortexpression"] = e.SortExpression;

        if (ViewState["sortdirection"] == null)
        {
            ViewState["sortdirection"] = "asc";
        }
        else
        {
            if (ViewState["sortdirection"].ToString() == "asc")
            {
                ViewState["sortdirection"] = "desc";
            }
            else
            {
                ViewState["sortdirection"] = "asc";
            }
        }

        BindGridView(dirPath, ViewState["sortexpression"].ToString());
    }

    public void BindGridView(string dirPath, string sortExpression)
    {
        if (ViewState["sortdirection"] == "asc")
            SortGridView(GridView1, Function.DirToDataTable(dirPath), sortExpression, false);
        else
            SortGridView(GridView1, Function.DirToDataTable(dirPath), sortExpression, true);
    }

    public static void SortGridView(GridView gv, DataTable dt, string orderByString, bool isAsc)
    {
        DataView dv = dt.DefaultView;
        if (orderByString != null)
        {
            if (orderByString.ToString().Trim().Length > 0)
            {
                if (isAsc)
                    dv.Sort = orderByString + " asc";
                else
                    dv.Sort = orderByString + " desc";
            }
        }
        gv.DataSource = dv;
        gv.DataBind();
    }

    protected void Del_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            CheckBox cbx = GridView1.Rows[i].FindControl("Item") as CheckBox;
            if (cbx.Checked)
            {
                FileInfo oFile = new FileInfo(cbx.ToolTip.ToString().Trim());
                if (oFile.Exists)
                {
                    oFile.Delete();
                    BindGridView(dirPath, ViewState["sortexpression"].ToString());
                }
            }
        }
    }

    protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Del")
        {
            if (e.CommandArgument != null)
            {
                string strFilename = e.CommandArgument.ToString().Trim();
                FileInfo oFile = new FileInfo(strFilename);
                if (oFile.Exists)//判断文件是否存在
                {
                    oFile.Delete();
                    BindGridView(dirPath, ViewState["sortexpression"].ToString());
                }
            }
            else
            {
                JScript.Alert("对不起您操作的文件不存在。");
            }
        }
    }
}

public class Function{

//将虚拟目录转换成DataTable
    public static DataTable DirToDataTable(string strDir)
    {
        try
        {
            DataTable FileTable = new DataTable();

            FileTable.Columns.Add(new DataColumn("name", typeof(String)));
            FileTable.Columns.Add(new DataColumn("size", typeof(Int32)));
            FileTable.Columns.Add(new DataColumn("type", typeof(String)));
            FileTable.Columns.Add(new DataColumn("date", typeof(DateTime)));
            FileTable.Columns.Add(new DataColumn("fullname", typeof(String)));
            FileTable.Columns.Add(new DataColumn("url", typeof(String)));

            if (!Directory.Exists(strDir))
            {
                DirectoryInfo Dir = new DirectoryInfo(HttpContext.Current.Server.MapPath(strDir));

                foreach (FileInfo f in Dir.GetFiles())
                {
                    DataRow FileRow = FileTable.NewRow();
                    FileRow[0] = f.Name;
                    FileRow[1] = f.Length / 1024;
                    FileRow[2] = f.Extension ?? "unknow";
                    FileRow[3] = f.LastWriteTime;
                    FileRow[4] = f.FullName;
                    FileRow[5] = strDir + f.Name;
                    FileTable.Rows.Add(FileRow);
                }
            }

            return FileTable;
        }
        catch
        {
            return null;
        }
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值