2010-02-11 5 views

ответ

37
System.IO.Directory myDir = GetMyDirectoryForTheExample(); 
int count = myDir.GetFiles().Length; 
84

Вы можете использовать метод Directory.GetFiles

Также см Directory.GetFiles Method (String, String, SearchOption)

Вы можете указать опцию поиска в этой перегрузки.

TopDirectoryOnly: Включает только текущий каталог в поиске.

AllDirectories: Включает текущий каталог и все подкаталоги в операции поиска. Этот параметр включает точки повторной обработки, такие как установленные диски и символические ссылки в поиске.

// 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; 
+0

Могу ли я предложить использовать «*» для соответствия файлам, иначе файлы без расширений не будут включены в счет. –

17

гладкий метод woud будет использовать LINQ:

var fileCount = (from file in Directory.EnumerateFiles(@"H:\iPod_Control\Music", "*.mp3", SearchOption.AllDirectories) 
         select file).Count(); 
+4

Вы можете просто написать: var fileCount = Directory.EnumerateFiles (@ "H: \ iPod_Control \ Music", "* .mp3", SearchOption.AllDirectories) .Count(); – AndrewS

8
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath"); 
int count = dir.GetFiles().Length; 

Вы можете использовать это.

3

Чтение PDF файлов из каталога:

var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf"); 
if (list.Length > 0) 
{ 

} 
-1

Чтобы получить количество определенных расширений типа с использованием LINQ вы могли бы использовать этот простой код:

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()) 
0

Попробуйте следующий код, чтобы получить количество файлов в папка

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