最近在討論區看到"檔案列表順序"的問題...
小弟去找到一個不錯的方法..分享給大家呀..
asp.net(c#)
SortFileList.aspx
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="SortFileList.aspx.cs" Inherits="SortFileList" %>
- <!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>SortFileList</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- </div>
- </form>
- </body>
- </html>
SortFileList.aspx.cs
- using System;
- using System.Data;
- using System.Configuration;
- using System.Collections;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Web.UI.HtmlControls;
- using System.IO;
- public partial class SortFileList : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- DirectoryInfo dirinfo = new DirectoryInfo(MapPath("~"));
- FileInfo[] sortList = dirinfo.GetFiles();
- Array.Sort(sortList, new MyDateSorter());
- foreach (FileInfo item in sortList)
- {
- Response.Write(item.FullName + "<br" + " />");
- }
- }
- }
- public class MyDateSorter : IComparer
- {
- #region IComparer Members
- public int Compare(object x, object y)
- {
- if (x == null && y == null)
- {
- return 0;
- }
- if (x == null)
- {
- return -1;
- }
- if (y == null)
- {
- return 1;
- }
- FileInfo xInfo = (FileInfo)x;
- FileInfo yInfo = (FileInfo)y;
- //依名稱排序
- return xInfo.FullName.CompareTo(yInfo.FullName);//遞增
- //return yInfo.FullName.CompareTo(xInfo.FullName);//遞減
- //依修改日期排序
- //return xInfo.LastWriteTime.CompareTo(yInfo.LastWriteTime);//遞增
- //return yInfo.LastWriteTime.CompareTo(xInfo.LastWriteTime);//遞減
- }
- #endregion
- }
執行結果:(依名稱遞增排序)
參考網址:http://forums.asp.net/p/84867/84867.aspx
引用URL
http://www.dotblogs.com.tw/puma/archive/2008/08/07/4834.aspx
複製網址