Program Club

특정 디렉토리의 경로없이 파일 이름 가져 오기

proclub 2020. 12. 11. 18:59
반응형

특정 디렉토리의 경로없이 파일 이름 가져 오기


전체 경로없이 디렉토리 (및 하위 디렉토리)의 모든 파일 이름을 어떻게 얻을 수 있습니까? Directory.GetFiles (...) 는 항상 전체 경로를 반환합니다!


전체 경로에서 파일 이름을 추출 할 수 있습니다.

.NET 3, 파일 이름 만

var filenames3 = Directory
                .GetFiles(dirPath, "*", SearchOption.AllDirectories)
                .Select(f => Path.GetFileName(f));

.NET 4, 파일 이름 만

var filenames4 = Directory
                .EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
                .Select(Path.GetFileName); // <-- note you can shorten the lambda

디렉토리 내부의 상대 경로가있는 파일 이름을 반환합니다.

// - file1.txt
// - file2.txt
// - subfolder1/file3.txt
// - subfolder2/file4.txt

var skipDirectory = dirPath.Length;
// because we don't want it to be prefixed by a slash
// if dirPath like "C:\MyFolder", rather than "C:\MyFolder\"
if(!dirPath.EndsWith("" + Path.DirectorySeparatorChar)) skipDirectory++;

var filenames4s = Directory
                .EnumerateFiles(dirPath, "*", SearchOption.AllDirectories)
                .Select(f => f.Substring(skipDirectory));

LinqPad에서 확인 ...

filenames3.SequenceEqual(filenames4).Dump(".NET 3 and 4 methods are the same?");

filenames3.Dump(".NET 3 Variant");
filenames4.Dump(".NET 4 Variant");
filenames4s.Dump(".NET 4, subfolders Variant");

있습니다 *Files(dir, pattern, behavior)방법은 비 재귀로 단순화 할 수는 *Files(dir)하위 폴더가 중요하지 않은 경우 변형


Path.GetFileName 참조 :

지정된 경로 문자열의 파일 이름과 확장자를 반환합니다.

경로 클래스는 몇 가지 유용한 파일 이름 및 경로 방법이있다.


원하는 Path.GetFileName

파일 이름 (확장자 포함) 만 반환됩니다.

확장자없이 이름 만 원하면 다음을 사용하십시오. Path.GetFileNameWithoutExtension


전체 경로에서 파일 이름을 추출 할 수 있습니다.

var sections = fullPath.Split('\\');
var fileName = sections[sections.Length - 1];

string fileName = @"C:\mydir\myfile.ext";
string path = @"C:\mydir\";
string result;

result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
fileName, result);

result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'", 
path, result);

이 질문에 대한 몇 가지 정답이 있지만이 솔루션은 다음과 같이 찾을 수 있습니다.

string[] files = Directory.EnumerateFiles("C:\Something", "*.*")
                 .Select(p => Path.GetFileName(p))
                 .Where(s => s.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase) || s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)).ToArray();

감사


DirectoryInfo 개체를 만들고 검색 패턴을 사용하여 열거 한 다음 배열처럼 처리합니다.

string filePath = "c:\Public\";
DirectoryInfo apple = new DirectoryInfo(@filepath);
foreach (var file in apple.GetFiles("*")
{
   //do the thing
   Console.WriteLine(file)
}

클래스의 GetFiles()메소드를 사용하여 특정 디렉토리의 파일 이름을 얻을 수 있습니다 DirectoryInfo. 다음은 모든 파일을 나열하는 샘플 예제와 특정 디렉터리의 세부 정보입니다.

System.Text.StringBuilder objSB = new System.Text.StringBuilder();
    System.IO.DirectoryInfo directory = new System.IO.DirectoryInfo("d:\\");
    objSB.Append("<table>");
    objSB.Append("<tr><td>FileName</td>" + 
                 "<td>Last Access</td>" + 
                 "<td>Last Write</td>" + 
                 "<td>Attributes</td>" + 
                 "<td>Length(Byte)</td><td>Extension</td></tr>");

    foreach (System.IO.FileInfo objFile in directory.GetFiles("*.*"))
    {
        objSB.Append("<tr>");

        objSB.Append("<td>");
        objSB.Append(objFile.Name);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.LastAccessTime);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.LastWriteTime);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.Attributes);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.Length);
        objSB.Append("</td>");

        objSB.Append("<td>");
        objSB.Append(objFile.Extension);
        objSB.Append("</td>");

        objSB.Append("</tr>");
    }
    objSB.Append("</table>");

    Response.Write(objSB.ToString());

이 예제는 HTML 테이블 구조로 파일 목록을 표시합니다.

참고 URL : https://stackoverflow.com/questions/6817639/get-filenames-without-path-of-a-specific-directory

반응형