C # traverse all objects in a specified folder
C # traverse all objects in a specified folder
DirectoryInfo TheFolder = new DirectoryInfo (folderFullName );
// Traverse folders
Foreach (DirectoryInfo NextFolder in TheFolder. GetDirectories ())
This. listBox1.Items. Add (NextFolder. Name );
// Traverse objects
Foreach (FileInfo NextFile in TheFolder. GetFiles ())
This. listBox2.Items. Add (NextFile. Name );
How to obtain files and subdirectories in a specified directory
1. DirectoryInfo. GetFiles (): Get the files in the directory (excluding subdirectories). The returned type is FileInfo []. wildcard search is supported;
2. DirectoryInfo. GetDirectories (): Obtain the subdirectory of the directory (excluding the subdirectory). The return type is DirectoryInfo []. Wildcards are supported;
3. DirectoryInfo. GetFileSystemInfos (): gets the files and subdirectories under the specified directory (excluding subdirectories). The return type is FileSystemInfo []. Wildcards are supported;
How to obtain the basic information of a specified object;
FileInfo. Exists: obtains whether the specified file Exists;
FileInfo. Name, FileInfo. Extensioin: get the file Name and extension;
FileInfo. FullName: Get the full-qualified name of the file (full path );
FileInfo. Directory: Directory where the file is located. The returned type is DirectoryInfo;
FileInfo. DirectoryName: Obtain the path of the directory where the file is located (full path );
FileInfo. Length: get the file size (number of bytes );
FileInfo. IsReadOnly: Gets whether the file is read-only;
FileInfo. Attributes: gets or sets the Attributes of a specified file. The returned type is FileAttributes enumeration, which can be a combination of multiple values.
FileInfo. CreationTime, FileInfo. LastAccessTime, and FileInfo. LastWriteTime are used to obtain the file creation time, access time, and modification time respectively;
Assume that the folder is in drive F, and the code is as follows. Output the file name to a ListBox.
Using System. data; using System. drawing; using System. linq; using System. text; using System. windows. forms; using System. IO; namespace WindowsFormsApplication1 {public partial class Form1: Form {public Form1 () {InitializeComponent ();} private void button2_Click (object sender, EventArgs e) {DirectoryInfo theFolder = new DirectoryInfo (@ "F: \ a \"); DirectoryInfo [] dirInfo = theFolder. getDirectories (); // traverse the folder foreach (DirectoryInfo NextFolder in dirInfo) {// this. listBox1.Items. add (NextFolder. name); FileInfo [] fileInfo = NextFolder. getFiles (); foreach (FileInfo NextFile in fileInfo) // traverses the file this. listBox2.Items. add (NextFile. name );}}}}