如何枚举目录及其内容
本示例阐释如何使用 DirectoryInfo 类创建目录列表。这是一个很好的方法,可以为用户或报告快速列出文件,或查找有关特定目录的基本信息。当与 FileInfo 组合使用时,可以获得需要的关于某特定目录中文件和目录的所有信息。
浏览给定目录的文件和子目录的功能对于许多编程任务都是很基本的。本“快速入门”向您展示如何使用 FileInfo 和 DirectoryInfo 类。为什么不是 File 和 Directory 类?本“快速入门”旨在显示给定文件的大小、创建日期等信息。在这种情况下,使用 FileInfo 和 DirectoryInfo 对象更方便。File 类集中在使用非实例化(C# 中的静态,或 Visual Basic 中的共享)方法上,而 FileInfo 类基于 FileInfo 对象的实例来提供方法。Directory 和 DirectoryInfo 类似。
第一项任务解释如何创建 DirectoryInfo 对象的实例(基于当前目录),然后查找该目录的完全限定路径。接下来,可以生成当前目录内所有文件和目录的表,以便它在该表的顶端输出当前目录的完整路径。我们使用 Path 类的 GetFullPath 方法来确定目录的完全限定路径。
//Do not forget your using statements at the top of your code.
using System;
using System.IO;
//…
// make an object which represents our current directory. The dot (".") represents this directory
DirectoryInfo dir = new DirectoryInfo(".");
// make the header for our table, letting the user know the path we are in…
Console.WriteLine("Following is a listing for directory: &leftsign;0&rightsign;", Path.GetFullPath(dir.ToString()));
\’目录内的对象可以是文件或目录。您可以迭代通过目录两次,先查找文件,接着查找目录。另一个解决方案是使用 FileSystemInfo 对象,它可以表示 FileInfo 或 DirectoryInfo 对象。这意味着您只须迭代通过该集合一次。然后,调用在上面代码中创建的对象的 GetFileSystemInfos 方法,它返回 FileSystemInfo 对象的数组。可使用 Foreach(Visual Basic 中为 For Each)迭代通过该数组,如以下代码所示。
// loop through our array of FileSysteminfo objects
foreach(FileSystemInfo fsi in dir.GetFileSystemInfos()) &leftsign;
// … the code in the following samples goes here.
&rightsign;
这样一来现在就可看到 FileSystemInfo 数组的每个元素是哪种类型的对象,并相应进行处理。首先测试 FileSystemObject 的实例,看它是否是文件。如果是,创建 FileInfo 对象的一个新实例来表示它。这使您可以调用特定于该对象类型的方法。如果不这样做,则不能调用 Length 之类的属性,该属性并不存在于 FileSystemInfo 中。相反,CreationTime 是 FileSystemInfo 对象的一个属性,这便是可以在输入 If 语句之前处理它的原因,而不管您是否有文件或目录。
请注意,您在缩短显示给用户的名称,主要是为了节省屏幕空间。由于可能存在文件访问异常或其他相关异常,所以请在 Try 块内执行该代码,以确保它不会异常结束。将该代码与前面示例中的代码放在一起,便有了您的程序(当然,一个方法内一次)。注意这只展示了如何处理文件。
try &leftsign;
DateTime creationTime = fsi.CreationTime;
int subLength = 25;
if (fsi is FileInfo) &leftsign; // check to see if the current object is a file…
FileInfo f = (FileInfo)fsi;
// this if statement simply ensures that we do not shorten the
// name of the file too much!
if (f.Name.Length < subLength)
subLength = f.Name.Length;
&rightsign;
string name = f.Name.Substring(0, subLength);
long size = f.Length;
// format the output to the screen
Console.WriteLine("&leftsign;0, -25&rightsign; &leftsign;1,-12:N0&rightsign; &leftsign;2, -12&rightsign; &leftsign;3,-20:g&rightsign;",
name, (size + " KB").PadLeft(12), "File", creationTime);
&rightsign;
else &leftsign; // it must be a directory
// …
&rightsign;
&rightsign; catch (Exception) &leftsign;&rightsign; // ignore errors such as \’file being used\’ etc…
摘要
可以使用 FileInfo 和 DirectoryInfo 来处理文件和目录,尽管也可以使用 File 和 Directory 作为备选项。通过操作基于信息的对象,您需要类的实例,但可方便地获取关于文件或目录的特定信息(如大小或创建日期)。
历史博文
- 20080919 xp logon ui - 2009
- 20070813 命名规范 注释标签 - 2008
- 1214 microapmddt.dll UPX 流氓 - 2007
- 0216 tortoisecvs ssh putty autoauth - 2006
- gmail zip rar google MSCOMM_ONCOMM - 2005
- 如何监视文件系统更改 - 2005