폴더의 파일 수


80

C #과 함께 ASP.NET을 사용하여 폴더에서 파일 수를 얻으려면 어떻게합니까?

답변:


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

3
디렉토리에 int.MaxValue 파일보다 많은 파일이 포함 된 경우 어떻게됩니까?
Mel Gerats

2
자원에 대한 가볍다 더 최신의 솔루션의 경우, 백작에 의해 EnumerateFiles에 의해 GetFiles에 () () 및 길이를 대체 ()
relatively_random

128

Directory.GetFiles 메서드를 사용할 수 있습니다.

Directory.GetFiles 메서드 (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;

파일 일치에 "*"를 사용하는 것이 좋습니다. 그렇지 않으면 확장자가없는 파일은 계산에 포함되지 않습니다.
Nick Bull

여기에는 하위 폴더 수가 포함 된 것 같습니다. 그건 내가 한 하위 폴더 및 그렇지 않으면 빈 디렉토리에이 반환 1. 가지고있다
수 종류의 새로운 사용자

@MichaelPotter desktop.ini를 세는 것이 가능합니까?
Heriberto Lugo

자원에 대한 가볍다 더 최신의 솔루션의 경우, 백작에 의해 EnumerateFiles에 의해 GetFiles에 () () 및 길이를 대체 ()
relatively_random

22

가장 매끄러운 방법은 LINQ 를 사용하는 것입니다 .

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

5
다음과 같이 작성할 수 있습니다. var fileCount = Directory.EnumerateFiles (@ "H : \ iPod_Control \ Music", "* .mp3", SearchOption.AllDirectories) .Count ();
AndrewS 2015

1
방대한 파일 모음의 경우이 방법을 권장했습니다. 이 접근 방식은 메모리를 절약합니다. GetFile플랫 메모리 공간이 필요한 메서드 create string []. 조심하세요 :)
hsd

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

이것을 사용할 수 있습니다.


8

디렉토리에서 PDF 파일 읽기 :

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

}

불필요하게 목록을 정의합니다. 이 작업을 수행해야하는 경우 Directory.Getfiles (@ "C : \ ScanPDF", "* .PDF") 수> 0.
스테판 마이어

@StefanMeyer 아니 당신은 ... 나중에 목록을 사용하여 원하지 경우
인 Guille 바우 자

@GuilleBauza 문제는 그것들을 사용하려면, PDF 파일에 포함되지 것이었다)
스테판 마이어

당신이 그것을 사용하지 않을 경우 네,하지만 계산의 포인트는 ... 무엇
인 Guille 바우 자

3

.NET 메서드 Directory.GetFiles (dir) 또는 DirectoryInfo.GetFiles ()는 총 파일 수를 얻는 데 그리 빠르지 않습니다. 이 파일 수 방법을 매우 많이 사용하는 경우 WinAPI를 직접 사용하여 약 50 %의 시간을 절약 할 수 있습니다.

다음은 C # 메서드에 대한 WinAPI 호출을 캡슐화하는 WinAPI 접근 방식입니다.

int GetFileCount(string dir, bool includeSubdirectories = false)

완전한 코드 :

[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;
}

내 컴퓨터에서 13000 개의 파일이있는 폴더에서 검색 할 때-평균 : 110ms

int fileCount = GetFileCount(searchDir, true); // using WinAPI

.NET 기본 제공 메서드 : Directory.GetFiles (dir)-평균 : 230ms

int fileCount = Directory.GetFiles(searchDir, "*", SearchOption.AllDirectories).Length;

참고 : 하드 드라이브가 섹터를 찾는 데 약간 더 오래 걸리기 때문에 두 방법 중 하나를 처음 실행하면 각각 60 %-100 % 느려집니다. 후속 호출은 Windows에서 세미 캐시됩니다.


대단한 해결책이지만 작동하게하려면 다음 편집을 권장합니다. |||||||||||| add public static long fileCount = 0; |||||||||||| // int fileCount = 0; // comment out
Markus

3
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

2

폴더의 파일 수를 얻으려면 다음 코드를 시도하십시오.

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



-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())
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.