利用ASP.NET的Directory.GetFiles來取得特定副檔名,並結合ArrayList將檔案資訊綁定到GridView裡

最近又在小舖看到有關這方面的問題...
此範例主要的功能就是利用Directory.GetFiles將某個目錄裡的特定副檔名檔案取出放置在arraylist裡..
並且將arraylist與gridview結合...列出檔案的所有資訊....
再加上一個DropDownList來選擇圖片檔案,並顯示此圖片......c#範例...

最近又在小舖看到有關這方面的問題...
此範例主要的功能就是利用Directory.GetFiles將某個目錄裡的特定副檔名檔案取出放置在arraylist裡..
並且將arraylist與gridview結合...列出檔案的所有資訊....
再加上一個DropDownList來選擇圖片檔案,並顯示此圖片......c#範例...

DirectoryFileFilter.aspx

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="DirectoryFileFilter.aspx.cs" Inherits="DirectoryFileFilter" %>
   2:   
   3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:   
   5:  <html xmlns="http://www.w3.org/1999/xhtml" >
   6:  <head runat="server">
   7:      <title>DirectoryFileFilter</title>
   8:  </head>
   9:  <body>
  10:      <form id="form1" runat="server">
  11:      <div>
  12:          <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
  13:          </asp:DropDownList>
  14:          <br />
  15:          <asp:GridView ID="GridView1" runat="server">
  16:          </asp:GridView>
  17:          <asp:Image ID="Image1" runat="server" /></div>
  18:      </form>
  19:  </body>
  20:  </html> 

DirectoryFileFilter.aspx.cs

   1:  using System;
   2:  using System.Data;
   3:  using System.Configuration;
   4:  using System.Collections;
   5:  using System.Web;
   6:  using System.Web.Security;
   7:  using System.Web.UI;
   8:  using System.Web.UI.WebControls;
   9:  using System.Web.UI.WebControls.WebParts;
  10:  using System.Web.UI.HtmlControls;
  11:  using System.IO;
  12:   
  13:  public partial class DirectoryFileFilter : System.Web.UI.Page
  14:  {
  15:      protected void Page_Load(object sender, EventArgs e)
  16:      {
  17:          if (!IsPostBack)
  18:          {
  19:              ArrayList fileArray = new ArrayList();
  20:              FileInfo info;
  21:              string[] files;
  22:   
  23:              //指定根目錄,取出所以副檔名為jpg的檔案清單
  24:              files = Directory.GetFiles(Server.MapPath("~/"), "*.jpg");
  25:   
  26:              //將每一個檔案資訊加入ArrayList裡
  27:              foreach (string item in files)
  28:              {
  29:                  info = new FileInfo(item);
  30:                  fileArray.Add(info);
  31:   
  32:                  //將檔案資訊加入DropDownList
  33:                  this.DropDownList1.Items.Add(new ListItem(info.Name));
  34:   
  35:              }
  36:   
  37:              this.GridView1.DataSource = fileArray;
  38:              this.GridView1.DataBind();
  39:          }
  40:      }
  41:      protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
  42:      {
  43:          this.Image1.ImageUrl = this.DropDownList1.SelectedValue;
  44:      }
  45:  }

執行結果:

DirectoryFileFilter

參考來源:ASP.NET Directory Lister

原始程式碼:DirectoryFileFilter.rar