File count from a folder

Viewed 220055

How do I get number of Files from a folder using ASP.NET with C#?

12 Answers

You can use the Directory.GetFiles method

Also see Directory.GetFiles Method (String, String, SearchOption)

You can specify the search option in this overload.

TopDirectoryOnly: Includes only the current directory in a search.

AllDirectories: Includes the current directory and all the subdirectories in a search operation. This option includes reparse points like mounted drives and symbolic links in the search.

// searches the current directory and sub directory
int fCount = Directory.GetFiles(path, "*", SearchOption.AllDirectories).Length;
// searches the current directory
int fCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length;
System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;
int fileCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; // Will Retrieve count of all files in directry and sub directries

int fileCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; // Will Retrieve count of all files in directry but not sub directries

int fileCount = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories).Length; // Will Retrieve count of files XML extension in directry and sub directries
int filesCount = Directory.EnumerateFiles(Directory).Count();

Try following code to get count of files in the folder

string strDocPath = Server.MapPath('Enter your path here'); 
int docCount = Directory.GetFiles(strDocPath, "*", 
SearchOption.TopDirectoryOnly).Length;

The System.IO namespace provides such a facility. It contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.

For example, if you wanted to count the number of files in the C:\ directory, you would say (Note that we had to escape the '\' character with another '\'):

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("C:\\");
int count = dir.GetFiles().Length;

You could also escape the '\' character by using the verbatim string literal whereby anything in the string that would normally be interpreted as an escape sequence is ignored, i.e. instead of ("C:\\"), you could say, (@"C:\")

If you are using MVC, and your directory exists inside your project structure and in the build when it is released on IIS for deployment, then you can use the following method to get the count of files in a specified directory:

string myFilesDir = System.Web.Hosting.HostingEnvironment.MapPath("~/MyServerDirectory/");
var countFiles = (from file in Directory.EnumerateFiles(myFilesDir, "*", SearchOption.AllDirectories)
                 select file).Count();
Related