利用DataGrid显示某目录下的所有文件

- 中国WEB开发者网络 (http://www.webasp.net)
-- 技术教程 (http://www.webasp.net/article/)
--- 利用DataGrid显示某目录下的所有文件 (http://www.webasp.net/article/27/26733.htm)
-- 作者:未知
-- 发布日期: 2005-09-29

.NET Framework提供两个访问目录信息的类和两个访问文件信息的类,钥访问目录,可以使用Directory类,也可以使用DirectoryInfo类,对应于文件,也有File类和FileInfo类。这两个类之间的区别在于返回的信息和使用的方法不同。Directory和File类属于静态类,在使用时你不必创建实例,例如:要删除文件,可以File.Delete(filePath),要检测文件夹是否存在可以Directory.Exists(directoryPath)。而带Info的类在使用时必须先进行实例化,并在构造函数里指名文件名字或者目录名字,因此,删除文件可以用Dim myFile as File = New File(filePath),myFile.Delete()。

这两个类都提供了得到一个文件夹下的所有文件或者某种扩展名的文件的方法,即GetFiles()。

' --- Directory 例子 ---- Dim files() as String = Directory.GetFiles(directoryPath[, optionalWildCard]) ' --- DirectoryInfo 例子 ---- Dim myDir as DirectoryInfo = New DirectoryInfo(directoryPath) Dim fileInfos() as FileInfo = myDir.GetFiles([optionalWildCard])

值得注意的是,两者返回的类型是不同的,一个是String类型的数组,另外一个是FileInfo类型的数组。下面就是绑定的方法:

VB.NET

<%@ Import Namespace="System.IO" %> <script language="<a href="http://www.chinaitpower.com/Dev/Programme/VB/index.html" target="_blank">VB</a>" runat="server"> Sub Page_Load(sender as Object, e as EventArgs) Dim dirInfo as New DirectoryInfo(Server.MapPath("")) articleList.DataSource = dirInfo.GetFiles("*.<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>x") articleList.DataBind() End Sub </script> <<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>:DataGrid runat="server" id="articleList" Font-Name="Verdana" AutoGenerateColumns="False" AlternatingItemStyle-BackColor="#eeeeee" HeaderStyle-BackColor="Navy" HeaderStyle-ForeColor="White" HeaderStyle-Font-Size="15pt" HeaderStyle-Font-Bold="True"> <Columns> <<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>:HyperLinkColumn DataNavigateUrlField="Name" DataTextField="Name" HeaderText="<a href="http://www.chinaitpower.com/Soft/Tools/File/index.html" target="_blank">文件</a>名" /> <<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>:BoundColumn DataField="LastWriteTime" HeaderText="最后修改时间" ItemStyle-HorizontalAlign="Center" DataFormatString="{0:d}" /> <<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>:BoundColumn DataField="Length" HeaderText="<a href="http://www.chinaitpower.com/Soft/Tools/File/index.html" target="_blank">文件</a>大小" ItemStyle-HorizontalAlign="Right" DataFormatString="{0:#,### 字节}" /> </Columns> </<a href="http://www.chinaitpower.com/Dev/Web/Asp/index.html" target="_blank">asp</a>:DataGrid>

webasp.net