Gets the number of all files in a directory (including files under subdirectories) (C #)

Source: Internet
Author: User
Tags foreach

Previously wrote a directory through the calculation of all files and subdirectories to obtain the number of files in a directory, the result found that the speed is very slow, far less than the system itself in the directory properties of the speed shown inside.

int filenum = 0;
/**////<summary>
Gets the number of all files in a directory, including files under subdirectories
</summary>
<param name= "Srcpath" ></param>
<returns></returns>
public int Getfilenum (string srcpath)
{
Try
{

Gets a list of files in the source directory that contains an array of files and directory paths
string[] filelist = System.IO.Directory.GetFileSystemEntries (Srcpath);
Iterate through all the files and directories
foreach (string file in FileList)
{
First as directory processing if there is this directory, recall Getfilenum (string srcpath)
if (System.IO.Directory.Exists (file))
Getfilenum (file);
Else
filenum++;
}

}
catch (Exception e)
{
MessageBox.Show (E.tostring ());
}
return filenum;
}
Recently found a more efficient way, just traverse the directory to get the number of files, now share
System.IO.DirectoryInfo dirinfo = new System.IO.DirectoryInfo (Dirpath);

public static int Getfilescount (System.IO.DirectoryInfo dirinfo)
{
int totalfile = 0;
Totalfile + = Dirinfo.getfiles (). Length;
foreach (System.IO.DirectoryInfo subdir in Dirinfo.getdirectories ())
{
Totalfile + + getfilescount (subdir);
}
return totalfile;
}



Related Article

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.