c# 获取指定目录下的所有文件并显示在网页上

参考文献:

FileInfo 的使用  https://msdn.microsoft.com/zh-cn/library/system.io.fileinfo_methods(v=vs.110).aspx

网页表格的生成  http://www.w3school.com.cn/html/html_tables.asp

C# 通过文件扩展名获取图标和描述 http://www.csframework.com/archive/2/arc-2-20110514-1478.htm   http://www.codeproject.com/Articles/32059/WPF-Filename-To-Icon-Converter

C# 获取当前路径方法 http://www.cnblogs.com/JoshuaDreaming/archive/2010/11/25/1887996.html

C# 获取指定目录下所有文件信息、移动目录、拷贝目录 http://blog.csdn.net/vchao13/article/details/6200255

这个函数比较重要,递归获得指定目录下的所有文件信息,当然包括里面的子文件信息

    /// <summary>
    /// 返回指定目录下的所有文件信息
    /// </summary>
    /// <param name="strDirectory"></param>
    /// <returns></returns>
    public void GetAllFilesInDirectory(string strDirectory)
    {
        DirectoryInfo directory = new DirectoryInfo(strDirectory);
        DirectoryInfo[] directoryArray = directory.GetDirectories();
        FileInfo[] fileInfoArray = directory.GetFiles();
        if (fileInfoArray.Length > 0) listFiles.AddRange(fileInfoArray);
        foreach (DirectoryInfo _directoryInfo in directoryArray)
        {
            GetAllFilesInDirectory(_directoryInfo.FullName);//递归遍历  
        }
    }

 

    /// <summary>
    /// 拼接需要显示的HTML
    /// </summary>
    /// <param name="titleStr">标题名称</param>
    /// <param name="showStr">所有根目录</param>
    /// <returns>显示的HTML</returns>
    private string GetHtmlStr(string titleStr,string showStr)
    {
        string htmlStr = @"<html>
                             <head>
                              <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
                              <title>{0}</title>
                             </head>
                             <body>
                              <h1>{1}</h1>
                              {2}
                             </body>
                            </html>";
        htmlStr = String.Format(htmlStr, titleStr, titleStr, showStr);
        return htmlStr;
    }
View Code

这是一小段拼接HTML内容的代码...- -!看不懂的就问

GetAllFilesInDirectory(HttpContext.Current.Server.MapPath(dateStr));
_showStr.Append("<table border='1'>");
_showStr.Append("<tr><td>文件名</td><td>文件大小</td><td>创建时间</td><td>文件目录</td></tr>");
for(int i = 0; i<listFiles.Count; i++)
{
    string herf = listFiles[i].FullName.Substring(_urlStr.Length, listFiles[i].FullName.Length - _urlStr.Length);
    herf = herf.Replace('\\', '/');
    _showStr.Append("<tr><td><A HREF='" + herf + "'>" + listFiles[i].Name + "</A></td><td>" + listFiles[i].Length + "</td><td>" + listFiles[i].CreationTime + "</td><td>" + listFiles[i].FullName+ "</td></tr>");
}
_showStr.Append("</table>");
            
htmlStr = GetHtmlStr(_urlStr, _showStr.ToString());

Response.Write(htmlStr);
View Code

 

posted @ 2016-04-29 20:28  疯狂的delete  阅读(1278)  评论(0编辑  收藏  举报