2013-04-15 7 views
-4

디렉토리 또는 하위 디렉토리에 파일이 있는지 확인하고 싶습니다.디렉토리 또는 하위 디렉토리에 파일이 있는지 확인하십시오.

string[] filePaths = Directory.GetFiles(padserver, "*", SearchOption.AllDirectories); 
try { 
    DataContainer.bestaatal = false; 
    lusfilebestaat = 0; 
    while (DataContainer.bestaatal == false) { 
     filePaths[lusfilebestaat] = Path.GetFileName(filePaths[lusfilebestaat]); 
     if (filePaths[lusfilebestaat] == bestandsnaam) { 
      DataContainer.bestaatal = true; 
     } 
     lusfilebestaat = lusfilebestaat + 1; 
    } 
} 

내 서버에 파일이 많아서 작동하지만 느려집니다.

해결책이있는 사람이 있습니까?

+0

'bestandsnaam'이란 무엇입니까? – Habib

+0

Thats 파일 이름 – Joeri

+1

SO – Shrivallabh

답변

2

System.IO.File.Exists() 방법을 사용하십시오. msdn을 참조하십시오.

+0

whil this scan 하위 디렉토리에 있습니까? – Joeri

+0

@ 조에리 당신이 제공하는 경로는 반드시 완료되어야합니다. –

+0

@Joeri 파일의 경로를 전달해야합니다. 'test.txt'는 확실히 당신을 위해 서브 디렉토리를 검색하지 않을 것입니다. – Nolonar

0

이 당신에게

internal static bool FileOrDirectoryExists(string name) 
{ 
    return (Directory.Exists(name) || File.Exists(name)) 
} 

도움이 될 수도 또는 대안은 검색 기능을 직접 작성하는 것입니다,이 중 하나가 작동합니다 :

private bool FileExists(string rootpath, string filename) 
{ 
    if(File.Exists(Path.Combine(rootpath, filename))) 
     return true; 

    foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories)) 
    { 
     if(File.Exists(Path.Combine(rootpath, filename))) 
     return true; 
    } 

    return false; 
} 

private bool FileExistsRecursive(string rootPath, string filename) 
{ 
    if(File.Exists(Path.Combine(rootPath, filename))) 
     return true; 

    foreach (string subDir in Directory.GetDirectories(rootPath)) 
    { 
     return FileExistsRecursive(subDir, filename); 
    } 

    return false; 
} 

첫 번째는 여전히 첫번째 디렉토리 이름을 모두 꺼내서 하위 디렉토리가 많고 파일이 맨 위에있는 경우 속도가 느려질 수 있습니다.

두 번째는 재귀 적이며 '최악의 경우'시나리오에서는 속도가 느릴 수 있지만 중첩 된 하위 디렉토리가 많고 파일이 최상위 디렉토리에있는 경우 더 빠릅니다.

+0

uhm .. [Achs answer] (http://stackoverflow.com/a/3994534)를 바로 복사하셨습니까? – Default

관련 문제