.netFrameWork给我们提供了很多良好的文件操作类。
其中有一个地址操作类叫做Directory,其是一个静态类,使用这个类,将节省实例化的时间。
要获得一个文件夹下的所有文件,大约有两种方式:
(1)直接调用Directory类的静态方法。 string[] Directory.GetFiles(三个参数);其中第三个参数确定是否包含子目录

GetFiles(string path, string searchPattern, SearchOption searchOption)#region GetFiles(string path, string searchPattern, SearchOption searchOption)
//
// Summary:
// Returns the names of files in the specified directory that match the specified
// search pattern, using a value to determine whether to search subdirectories.
//
// Parameters:
// searchOption:
// One of the System.IO.SearchOption values that specifies whether the search
// operation should include all subdirectories or only the current directory.
//
// path:
// The directory to search.
//
// searchPattern:
// The search string to match against the names of files in path. The parameter
// cannot end in two periods ("..") or contain two periods ("..") followed by
// System.IO.Path.DirectorySeparatorChar or System.IO.Path.AltDirectorySeparatorChar,
// nor can it contain any of the characters in System.IO.Path.InvalidPathChars.
//
// Returns:
// A String array containing the names of files in the specified directory that
// match the specified search pattern. File names include the full path.
//
// Exceptions:
// System.UnauthorizedAccessException:
// The caller does not have the required permission.
//
// System.ArgumentNullException:
// path or searchpattern is null.
//
// System.IO.IOException:
// path is a file name.
//
// System.ArgumentException:
// path is a zero-length string, contains only white space, or contains one
// or more invalid characters as defined by System.IO.Path.InvalidPathChars.
// -or- searchPattern does not contain a valid pattern.
//
// System.IO.PathTooLongException:
// The specified path, file name, or both exceed the system-defined maximum
// length. For example, on Windows-based platforms, paths must be less than
// 248 characters and file names must be less than 260 characters.
//
// System.IO.DirectoryNotFoundException:
// The specified path is invalid (for example, it is on an unmapped drive).
public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption);
#endregion
(2)使用递归程序:找到其中的所有的子文件夹,子文件夹再调用函数本身获得其中的文件名。
使用两个函数string[] Directory.GetFiles()//三个参数,这里空着第三个参数,
和获得 子目录的函数 public static string[] GetDirectories(string path);
本文介绍如何利用.NET Framework中的Directory类获取指定文件夹及其子文件夹下的所有文件。通过Directory类的GetFiles方法,可以方便地实现文件搜索,并支持通配符匹配及是否递归搜索子目录的选择。

1086

被折叠的 条评论
为什么被折叠?



