.Net Framework 4.0: Enumerating file system objects

王朝学院·作者佚名  2009-10-29
窄屏简体版  字體: |||超大  

2009-10-27 20:07:44 | .net教程聚合

In my last posting I introduced new ReadLines() method and new overloads for WriteAllLines() method of File class. But there are more new stuff in System.IO namespace. In .Net Framework 4.0 Directory and DirectoryInfo class are able to enumerate files, directories and file system entries. In this posting I will show you these new features.

Let’s see now how to enumerate file system objects using new static methods of Directory class. There is one thing you should know. If you have to handle files and directories in same context then you should use EnumerateFileSystemEntries() method that enumerates both files and directories. The following example shows you how to enumerate different file system objects.

--------------------------------------------------------------------------------

static void Main(string[] args)

{

var path = Path.GetPathRoot(Environment.CurrentDirectory);

var files = Directory.EnumerateFiles(path);

var directories = Directory.EnumerateDirectories(path);

var entries = Directory.EnumerateFileSystemEntries(path);

Console.WriteLine("Files:");

foreach (var file in files)

Console.WriteLine(file);

Console.WriteLine("\r\nDirectories:");

foreach (var directory in directories)

Console.WriteLine(directory);

Console.WriteLine("\r\nEntries:");

foreach (var entry in entries)

Console.WriteLine(entry);

Console.ReadLine();

}

--------------------------------------------------------------------------------

You should get output like this (the path is root path of drive where application is located).

Files:

C:\autoexec.bat

C:\config.sys

C:\pagefile.sys

Directories:

C:\$Recycle.BinC:\Documents and Settings

C:\Install

C:\PerfLogs C:\Program Files

C:\ProgramData C:\Recovery C:\System Volume Information C:\Users C:\Windows

Entries:

C:\$Recycle.Bin

C:\autoexec.bat

C:\config.sys

C:\Documents and Settings

C:\Install

C:\pagefile.sys

C:\PerfLogs

C:\Program Files

C:\ProgramData

C:\Recovery

C:\System Volume Information

C:\Users

C:\Windows

These enumerating methods work better than ones that return arrays because requests to file system are made only when concrete object is asked from enumerator. I think these methods may be very good load balancers in applications that make heavy use of file system.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航