asp.net(C#)读取文件夹和子文件夹下所有文件,绑定到GRIDVIEW并排序 .

Asp部分:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyFiles_List.aspx.cs" Inherits="lbWeb.webAdmin.MyFiles_List" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>无标题页</title>

<script language="javascript" type="text/javascript">

function selectAll(obj)    {

var theTable = obj.parentElement.parentElement.parentElement;

var i;

var j = obj.parentElement.cellIndex;

for(i=0;i<theTable.rows.length;i++)

{

var objCheckBox = theTable.rows[i].cells[j].firstChild;

if(objCheckBox.checked!=null)objCheckBox.checked = obj.checked;

}

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

<table width="100%">

<tr>

<td>

文件管理

</td>

</tr>

<tr>

<td>

<asp:GridView Width="100%" runat="server" ID="gridFileList"

AutoGenerateColumns="false" CellPadding="4" ForeColor="#333333"

GridLines="None" OnRowDataBound="gridFileList_RowDataBound" AllowPaging="True"

PageSize="6" OnPageIndexChanging="gridFileList_PageIndexChanging"

AllowSorting="True" onsorting="gridFileList_Sorting" >

<Columns>

<asp:TemplateField>

<ItemStyle HorizontalAlign="Center" />

<HeaderTemplate>&nbsp;<input id="CheckAll" type="checkbox" onclick="selectAll(this);" />全选</HeaderTemplate>

<ItemTemplate>

<asp:CheckBox runat="server" ID="chkDel" />

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="序号" InsertVisible="False">

<ItemStyle HorizontalAlign="Center" />

<ItemTemplate>

<asp:Label ID="Label2" runat="server" Text='<%# this.gridFileList.PageIndex * this.gridFileList.PageSize + this.gridFileList.Rows.Count + 1%>'/>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="图片" InsertVisible="False">

<ItemStyle HorizontalAlign="Center" />

<ItemTemplate>

<asp:Image ID="ImgPath" runat="server" Width="150" Height="80" />

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField="FileName" HeaderText="名称" SortExpression="FileName" >

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

<asp:BoundField DataField="FileLength" HeaderText="大小" SortExpression="FileLength" >

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

<asp:BoundField DataField="FilePath" ShowHeader="false">

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

<asp:BoundField DataField="FileLastWriteTime" HeaderText="修改时间" SortExpression="FileLastWriteTime" >

<ItemStyle HorizontalAlign="Center" />

</asp:BoundField>

</Columns>

</asp:GridView>

</td>

</tr>

<tr>

<td align="center" class="sub_bg">

<asp:Button runat="server" ID="btnAdd" Text="添 加" OnClick="btnAdd_Click" />&nbsp;

<asp:Button runat="server" ID="btnDel" Text="删 除" OnClick="btnDel_Click" OnClientClick="return confirm('提示:确定要删除吗?');" />

</td>

</tr>

</table>

</div>

</form>

</body>

</html>

CS部分:

using System;

using System.Collections;

using System.Configuration;

using System.Data;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.IO;

using System.Text;

namespace lbWeb.webAdmin

{

public partial class MyFiles_List : System.Web.UI.Page

{

protected string File_List="";

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

//设定初始排序字段为文件修改时间FileLastWriteTime

gridFileList.Attributes.Add("SortExpression", "FileLastWriteTime");

gridFileList.Attributes.Add("SortDirection", "DESC");

BindGrid();

}

}

///<summary>

///要显示的文件扩展名

///</summary>

///<param name="type"></param>

///<returns></returns>

public bool checkFileType(string type)

{

bool FileType = false;

string[] type_ = new string[4];

type = type.ToLower();

type_[0] = ".jpg";

type_[1] = ".gif";

type_[2] = ".jpeg";

type_[3] = ".png";

//可在此添加上传文件的后缀名

for (int i = 0; i < type_.Length; i++)

{

if (type.Contains(type_[i].ToString()))

{

FileType = true;

}

}

return FileType;

}

///<summary>

///遍文件夹下的所有子文件夹下的文件

///</summary>

///<param name="ObjDirPath">文件夹</param>

public void GetFiles(string ObjDirPath)

{

DirectoryInfo SourceDir = new DirectoryInfo(ObjDirPath);

foreach (FileSystemInfo FSI in SourceDir.GetFileSystemInfos())

{

if (FSI is DirectoryInfo)

{

//如果是文件夹则递归

GetFiles(FSI.FullName);

}

else

{

//如果是符合要求的文件则垒加集合,因为我只要求显示图片文件,在checkFileType方法里定义要显示文件的扩展名

if (checkFileType(FSI.Extension))

{

//由于是物理路径,如e:/luobing_web/uploadfiles/picture/test.jpg这种形式,需要提取虚拟路径,如:../uploadfiles/picture/test.jpg

string FilePath = ""; //一步写来看起混乱,就分开写了

FilePath = FSI.FullName.ToLower();

FilePath = FilePath.Substring(FilePath.LastIndexOf("uploadfiles//"));

FilePath = "../"+FilePath.Replace("//", "/");//这里在路径前加了../,因为我的项目里页面文件和上传文件夹不是同级文件夹

File_List += FilePath + ",";

}

}

}

}

///<summary>

///构造DataTABLE来绑定GRIDVIEW

///</summary>

///<returns></returns>

public DataTable FileDataTable()

{

GetFiles(Server.MapPath(@"~/UploadFiles/"));

//构造DataTABLE

DataTable dt = new DataTable();

dt.Columns.Add(new DataColumn("FilePath", typeof(string)));

dt.Columns.Add(new DataColumn("FileName", typeof(string)));

dt.Columns.Add(new DataColumn("FileLength", typeof(string)));

dt.Columns.Add(new DataColumn("FileLastWriteTime", typeof(string)));

DataRow dr;

//将文件数组集合切割到数组

string[] dtaArry = File_List.Split(',');

for (int i = 0; i < dtaArry.Length; i++)

{

if (dtaArry[i].Trim() != "")//防空元素

{

dr = dt.NewRow();

dr[0] = dtaArry[i];//文件路径

dr[1] = Path.GetFileName(dtaArry[i]);//文件名

//获取文件大小

FileInfo FI = new FileInfo(Server.MapPath(@dtaArry[i]));

dr[2] = Convert.ToString(FI.Length / 1000)+"KB";//获取的是字节byte,还需要转换为千字节KB

dr[3] = FI.LastWriteTime;

dt.Rows.Add(dr);

}

}

return dt;

}

///<summary>

///绑定gridview

///</summary>

private void BindGrid()

{

//获取数据源

DataTable dtb = FileDataTable();

//排序

string SortDirection = gridFileList.Attributes["SortDirection"].ToString();

string SortExpression = gridFileList.Attributes["SortExpression"].ToString();

dtb.DefaultView.Sort = string.Format("{0} {1}", SortExpression, SortDirection);

//赋数据源并绑定

gridFileList.DataSource = dtb;

gridFileList.DataBind();

}

///<summary>

///添加

///</summary>

///<param name="sender"></param>

///<param name="e"></param>

protected void btnAdd_Click(object sender, EventArgs e)

{

Response.Redirect("MyFiles_Add.aspx");

}

///<summary>

///删除

///</summary>

///<param name="sender"></param>

///<param name="e"></param>

protected void btnDel_Click(object sender, EventArgs e)

{

try

{

FileInfo fileinfo;

bool IsSelect = false;

for (int i = 0; i < gridFileList.Rows.Count; i++)

{

GridViewRow row = gridFileList.Rows[i];

if (((CheckBox)row.FindControl("chkDel")).Checked)

{

IsSelect = true;

Image Img = (Image)gridFileList.Rows[i].Cells[0].FindControl("ImgPath");

fileinfo = new FileInfo(Request.MapPath(@Img.ImageUrl));

if (fileinfo.Exists)

{

fileinfo.Delete();

}

}

}

if (IsSelect)

{

ValueChecked.MessageBox(Page, "删除成功!");

}

else

{

ValueChecked.MessageBox(Page, "请选择要删除的行!");

}

}

catch

{

ValueChecked.MessageBox(Page, "删除失败!");

}

BindGrid();

}

///<summary>

///绑定数据行

///</summary>

///<param name="sender"></param>

///<param name="e"></param>

protected void gridFileList_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

Image Img = (Image)e.Row.Cells[0].FindControl("ImgPath");

Img.ImageUrl = e.Row.Cells[5].Text;

e.Row.Cells[5].Text="";

}

}

///<summary>

///分页

///</summary>

///<param name="sender"></param>

///<param name="e"></param>

protected void gridFileList_PageIndexChanging(object sender, GridViewPageEventArgs e)

{

gridFileList.PageIndex = e.NewPageIndex;

this.BindGrid();

}

///<summary>

///排序

///</summary>

///<param name="sender"></param>

///<param name="e"></param>

protected void gridFileList_Sorting(object sender, GridViewSortEventArgs e)

{

string sortExpression = e.SortExpression.ToString();

string sortdirection = "ASC";

if (sortExpression == gridFileList.Attributes["SortExpression"])

{

sortdirection = (gridFileList.Attributes["SortDirection"].ToString() == sortdirection ? "DESC" : "ASC");

}

gridFileList.Attributes["SortExpression"] = sortExpression;

gridFileList.Attributes["SortDirection"] = sortdirection;

this.BindGrid();

}

}

}

上一篇:【转发】du命令 实现Linux 某个文件夹下的文件按大小排序


下一篇:Python爬虫10-页面解析数据提取思路方法与简单正则应用