Method 1
The code is as follows: |
Copy code |
Private void forFileLength (DirectoryInfo directory) { DirectoryInfo [] directorys = directory. GetDirectories (); FileInfo [] files; Foreach (DirectoryInfo di in directorys) { ForFileLength (di ); } Files = directory. GetFiles (); Foreach (FileInfo file in files) { String temp = file. DirectoryName. ToString (); // The current path. String name = file. Name; // name of the file name } } |
Method 2
(1) create a new website. The Default Web form is Default. aspx.
(2) in Default. in aspx, a TextBox control, a Button control, and a Lable control are added to enter the path to traverse the folder, start to traverse the folder, obtain the number of files, and display the number of files to traverse.
(3) click the Get file quantity button to obtain the number of files in a specified folder, which is implemented by calling the custom method GetAllFiles. Add the following code to the Click event of the Get file count button:
The code is as follows: |
Copy code |
Int j = 0; Protected void button#click (object sender, EventArgs e) { DirectoryInfo dir = new DirectoryInfo (TextBox1.Text. ToString ()); Label1.Text = GetAllFiles (dir). ToString (); } |
The GetAllFiles method is a custom method to traverse the entire folder. The code is as follows:
The code is as follows: |
Copy code |
Public int GetAllFiles (DirectoryInfo dir) { FileSystemInfo [] fileinfo = dir. GetFileSystemInfos (); Foreach (FileSystemInfo I in fileinfo) { If (I is DirectoryInfo) { GetAllFiles (DirectoryInfo) I ); } Else { J ++; } } Return j; } |
Note: First, import the namespace System. IO. The GetAllFiles method can identify hidden files in the folder. The number of files traversed is the number of all files in the folder, including hidden files.
Method 3
The code is as follows: |
Copy code |
Protected void Page_Load (object sender, EventArgs e) { System. IO. DirectoryInfo dir = new System. IO. DirectoryInfo (Server. MapPath ("~ /")); TreeView treeView1 = new TreeView (); TreeNode nodeMain = OutPutNodes (dir, null ); TreeView1.Nodes. Add (nodeMain ); This. form1.Controls. Add (treeView1 ); } Private TreeNode OutPutNodes (System. IO. DirectoryInfo dir, TreeNode parentNode) { If (dir = null) Return null; TreeNode dirNode = new TreeNode (dir. Name ); System. IO. DirectoryInfo [] subDirs = dir. GetDirectories (); For (int I = 0; I <subDirs. Length; I ++) { OutPutNodes (subDirs [I], dirNode ); } System. IO. FileInfo [] files = dir. GetFiles (); For (int I = 0; I <files. Length; I ++) { DirNode. ChildNodes. Add (new TreeNode (files [I]. Name )); } If (parentNode = null) { Return dirNode; } Else { ParentNode. ChildNodes. Add (dirNode ); Return parentNode; } } |
Summary
To view files in a folder, you must use an important method in the DirectoryInfo class GetFileSystemInfos (), this method returns an array of strong FileSystemInfo objects in files and subdirectories that match the search criteria.