获取目录和子目录下文件

<%@ Page Language="C#" %>

<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">


    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string str = "d:\\网站测试";     //搜索的目录  
            if (str[str.Length - 1] != '\\')   //非根目录 
            {
                str += "\\";
            }
            FindFile(str);     //调用查找文件函数 
        }
    }

    /// <summary>
    /// 去某个目录下面的子文件和子目录下面的所有文件
    /// </summary>
    /// <param name="dir"></param>
    public void FindFile(string dir)//参数为指定的目录  
    {
        //在指定目录及子目录下查找文件,在listBox1中列出子目录及文件  
        DirectoryInfo Dir = new DirectoryInfo(dir);
        try
        {
            foreach (DirectoryInfo d in Dir.GetDirectories())     //查找子目录    
            {
                FindFile(Dir + d.ToString() + "\\");
                //ListBox1.Items.Add(Dir + d.ToString() + "\\");       //listBox1中填加目录名
            }
            foreach (FileInfo f in Dir.GetFiles("*.*"))             //查找文件  
            {
                string hz = System.IO.Path.GetExtension(f.ToString());//后去文件后缀名
                ListBox1.Items.Add(Dir + f.ToString()+"  后缀名:"+hz);     //listBox1中填加文件名  
            }
        }
        catch (Exception e)
        {

        }

    }
    /// <summary>
    /// 去某个目录下面的子文件
    /// </summary>
    private void findfile()
    {
        string[] dirs = Directory.GetDirectories(@"c:\");//路径  
        foreach (string dir in dirs)
        {
            Response.Write(dir+"<br />");
        }  
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="ListBox1" runat="server" Height="623px" Width="551px"></asp:ListBox>
    </div>
    </form>
</body>
</html>

posted @ 2010-04-05 15:45  王树羽  阅读(250)  评论(0编辑  收藏  举报