2013-04-24 3 views
-1

저는 프로그래밍에 초보자이며 C#으로 Windows 응용 프로그램을 만들어 폴더의 파일 수를 세는 데 도움이 필요합니다.폴더의 파일 수를 C로 계산하기 #

계산에 사용할 수있는 방법은 무엇입니까?

** 업데이트는 말한다 정확히 무엇을 2016년 2월 1일

, 폴더 안에 포함 된 파일의 amunt.

폴더에 3 개의 이미지 파일과 3 개의 텍스트 파일이 있으면 응용 프로그램에서 값 6을 반환해야합니다.

+1

응답 스택 오버 플로우 질문 224 2564. http://stackoverflow.com/questions/2242564/file-count-from-a-folder – emigue

+4

질문하기 전에 검색하십시오. –

+1

재귀? ... –

답변

4

System.IO.DirectoryInfo을 사용할 수 있습니다.

DirectoryInfo info = new DirectoryInfo(your folder path); 
info.GetFiles().Count(); 

또는

제안 :

info.EnumerateFiles(); 
+5

'EnumerateFiles'가 더 좋습니다. 특히'Count()'확장자를 사용하는 경우. – Jodrell

+0

@ Jodrell에게 감사드립니다. –

4

이 시도 :

var files = Directory.GetFiles(@"C:\SomeFolder").Length; 

는 디렉토리가 존재하지 않는 경우이 예외가 발생합니다주의하십시오.

0

DirectoryInfo 클래스가 도움이 될 것입니다. 행운

var info = new DirectoryInfo("D:\\"); 
var files = info.GetFiles(); 
var dirs = info.GetDirectories(); 
files.Length; 
dirs.Length; 
3
// This searches in the current directory and also sub directories 
int folderCount = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories).Length; 
// This searches only in the current directory 
int folderCount = Directory.GetFiles(path, "*.*", SearchOption.TopDirectory).Length; 

좋은!

+3

이것은 (귀하의 사용자 이름과 결합하여) 최고의 코멘트 중 상위 10 개 목록에 있어야합니다! –

+0

4 년 더 .. – Obama

+0

나는 독일인이기 때문에 오바마에 대해 매우 긍정적이다. 그러나 나는 상당수의 미국 시민이 "감사 오바마 !! - 헉"이라고 생각한다는 것을 알고있다.

10

Directory.GetFiles 메서드를 사용해야합니다. 당신이하지 않은, 그래서 만약

int fileCount = Directory.GetFiles(@"c:\MyDir\", "*.*", SearchOption.AllDirectories).Length; 

주 디렉토리가 DirectoryNotFoundException 존재하지 않는 경우에 Throw됩니다 : 당신이 너무, 하위 디렉토리를 검색하려면

int fileCount = Directory.GetFiles(@"C:\MyFolder").Length; 

, 다음과 같은 코드를 사용할 수 있습니다 디렉토리가 존재하는지 여부는 try ... catch 블록을 사용하거나 디렉토리가 있는지 확인하십시오. Directory.Exists method :

if (Directory.Exists(dirName)) 
{ 
    // Your code here 
} 
관련 문제