Reputation: 2499
How do I get number of Files from a folder using ASP.NET with C#?
Upvotes: 102
Views: 252338
Reputation: 8312
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();
Upvotes: 1
Reputation: 2225
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:\")
Upvotes: 0
Reputation: 181
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
Upvotes: 4
Reputation: 436
int filesCount = Directory.EnumerateFiles(Directory).Count();
Upvotes: 3
Reputation: 63
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;
Upvotes: 2
Reputation: 12912
.NET methods Directory.GetFiles(dir) or DirectoryInfo.GetFiles() are not very fast for just getting a total file count. If you use this file count method very heavily, consider using WinAPI directly, which saves about 50% of time.
Here's the WinAPI approach where I encapsulate WinAPI calls to a C# method:
int GetFileCount(string dir, bool includeSubdirectories = false)
Complete code:
[Serializable, StructLayout(LayoutKind.Sequential)]
private struct WIN32_FIND_DATA
{
public int dwFileAttributes;
public int ftCreationTime_dwLowDateTime;
public int ftCreationTime_dwHighDateTime;
public int ftLastAccessTime_dwLowDateTime;
public int ftLastAccessTime_dwHighDateTime;
public int ftLastWriteTime_dwLowDateTime;
public int ftLastWriteTime_dwHighDateTime;
public int nFileSizeHigh;
public int nFileSizeLow;
public int dwReserved0;
public int dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
[DllImport("kernel32.dll")]
private static extern IntPtr FindFirstFile(string pFileName, ref WIN32_FIND_DATA pFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindNextFile(IntPtr hFindFile, ref WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32.dll")]
private static extern bool FindClose(IntPtr hFindFile);
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
private const int FILE_ATTRIBUTE_DIRECTORY = 16;
private int GetFileCount(string dir, bool includeSubdirectories = false)
{
string searchPattern = Path.Combine(dir, "*");
var findFileData = new WIN32_FIND_DATA();
IntPtr hFindFile = FindFirstFile(searchPattern, ref findFileData);
if (hFindFile == INVALID_HANDLE_VALUE)
throw new Exception("Directory not found: " + dir);
int fileCount = 0;
do
{
if (findFileData.dwFileAttributes != FILE_ATTRIBUTE_DIRECTORY)
{
fileCount++;
continue;
}
if (includeSubdirectories && findFileData.cFileName != "." && findFileData.cFileName != "..")
{
string subDir = Path.Combine(dir, findFileData.cFileName);
fileCount += GetFileCount(subDir, true);
}
}
while (FindNextFile(hFindFile, ref findFileData));
FindClose(hFindFile);
return fileCount;
}
When I search in a folder with 13000 files on my computer - Average: 110ms
int fileCount = GetFileCount(searchDir, true); // using WinAPI
.NET built-in method: Directory.GetFiles(dir) - Average: 230ms
int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;
Note: first run of either of the methods will be 60% - 100% slower respectively because the hard drive takes a little longer to locate the sectors. Subsequent calls will be semi-cached by Windows, I guess.
Upvotes: 8
Reputation: 467
To get the count of certain type extensions using LINQ you could use this simple code:
Dim exts() As String = {".docx", ".ppt", ".pdf"}
Dim query = (From f As FileInfo In directory.GetFiles()).Where(Function(f) exts.Contains(f.Extension.ToLower()))
Response.Write(query.Count())
Upvotes: -2
Reputation: 187050
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;
Upvotes: 161
Reputation: 3346
The slickest method woud be to use LINQ:
var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories)
select file).Count();
Upvotes: 31
Reputation: 857
System.IO.Directory myDir = GetMyDirectoryForTheExample();
int count = myDir.GetFiles().Length;
Upvotes: 67
Reputation: 10562
Reading PDF files from a directory:
var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf");
if (list.Length > 0)
{
}
Upvotes: 9
Reputation: 7026
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;
You can use this.
Upvotes: 18