Folder recursion with C #

Source: Internet
Author: User

By Richard Carr, published at Http://www.blackwasp.co.uk/FolderRecursion.aspx

Some applications must read the folder structure beneath an existing folder or for an entire disk or attached device. The standard method in the Directory class can cause problems if used in the this. An alternative was to recursively read the folders.

Reading Folders

It was common to wish to read the entire folder structure of a disk when you were creating software that works with the file System. For example, wish to populate a TreeView control with the complete list of directories, or you might read the fold ERs in order to compare them with another directory or with a backup copy.

The Directory class, which is a standard type within the. NET framework, includes a method, named Getdirector IES, that's allows you to read the folders within a given path, and returning their names in a string array. You can use further methods of the Directory and File classes to work with the folders and their contents. An example of the GetDirectories method is shown below. This returns a list of folder names that can is found in the root of the the c:drive.

Nb:to Run this code is need to reference the System.IO namespace so add the directive, "using System.IO;" to Yo ur code.

string[] Folders = directory.getdirectories (@ "C: \");

To instruct the method to work recursively, reading the folders, their subfolders and directories beneath these until the Folder structure is exhausted, you can add the alldirectoriessearch option, as shown below:

string[] Folders = directory.getdirectories (@ "C: \", "*", searchoption.alldirectories);

Unfortunately, this has problems. Key amongst these is this some of the folders that you attempt to read could being configured so, the current user may no T access them. Rather than ignoring folders to which you had restricted access, the method throws anunauthorizedaccessexception . However, we can circumvent this problem by creating our own recursive folder search code.

Folder recursion

Let's start with some simple folder recursion code that recreates the flawed functionality of the getdirectories Method. We ll create it within a console application and show its activity by outputting folder name as they is examined. In a real application your could build and return a list or array, or use an iterator to return the values as they is requ Ired, thus avoiding the delay caused by reading large folder structures ahead of the time they is needed.

The code below shows the basic recursive method. The Main method callsShowallfoldersunder, passing in the starting path. In this case we is going to display all folders starting from the root of the c:drive.

Showallfoldersunder does the real work. When this method was called it uses the basic version of GetDirectories to obtain the folder list for directories immediate Ly within the provided path. It then loops through these folders, first displaying the name, then calling itself, passing the folder name, to look one Level deeper. This recursive nature causes all folders to being examined, unless an exception is thrown.

static void Main (string[] args) {    Console.WriteLine (@ "C: \");    Showallfoldersunder (@ "C: \", 0);} private static void Showallfoldersunder (string path, int indent) {    foreach (string folder in Directory.getdirectories (path))    {        Console.WriteLine ("{0}{1}", New string (' ', indent), Path.getfilename (folder));        Showallfoldersunder (folder, indent + 2);}    }

To avoid unauthorizedaccessexceptions stopping the execution, we need to add a try/catch block around the Foreach loop. We can use the this to catch only that type of exception and ignore it. This means, the folders to which, the user does not, has access'll not being displayed. The updated Showallfolders code is as follows.

private static void Showallfoldersunder (string path, int indent) {    try    {        foreach (string folder in Directory.getdirectories (path))        {            Console.WriteLine ("{0}{1}", New String (", indent), Path.getfilename ( folder));            Showallfoldersunder (folder, indent + 2);        }    }    catch (UnauthorizedAccessException) {}}
Reparse Points

Something else, we must deal with is  reparse points , or  junction points . Most disks used by Windows operating systems is formatted using THE  New technology File System , Or ntfs . This allows disks to is mounted in interesting ways. In addition to the usual assignment of drive letters, such as C:, disks can is mounted within folders. This means if you use Windows Explorer to browse to the C:\OtherDisk folder and you are seeing the contents of Anot Her disk or partition altogether.

Junction points generate a problem when recursively scanning folders; Drives can is mounted in such a through as to create infinite directory structures. For example, the disk containing your c:drive could is mounted within a folder named, "C:\Infinite". If you looked inside this folder you would find everything that's in the root of C:, including the "Infinite" folder. You could continue-to-drill down into that folder, each time seeing the same subfolders and files.

To avoid infinite loops, we need to check the A folder is not a junction point. We can do this by reading each folder ' s attributes and checking if it is a reparse point. To get the attributes we use the File.getattributes method, which returns an enumeration that represents a bit field. We can then use the bitwise AND operator to check for the existence of the reparsepointflag.

Using This information we can create the final version of Showallfoldersunder, as follows:

private static void Showallfoldersunder (string path, int indent) {    try    {        if (file.getattributes (path) & fileattributes.reparsepoint)!            = fileattributes.reparsepoint)        {            foreach (string folder in Directory.getdirectories (path))            {                Console.WriteLine (                    "{0}{1}", new String (', indent), Path.getfilename (folder));                Showallfoldersunder (folder, indent + 2);    }}} catch (UnauthorizedAccessException) {}}

Folder recursion with C #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.