program story

경로에서 각 폴더 이름을 어떻게 추출합니까?

inputbox 2020. 12. 3. 07:49
반응형

경로에서 각 폴더 이름을 어떻게 추출합니까?


내 길은 \\server\folderName1\another name\something\another folder\

경로에 몇 개의 폴더가 있고 폴더 이름을 모르는 경우 각 폴더 이름을 문자열로 추출하려면 어떻게해야합니까?

많은 감사


string mypath = @"..\folder1\folder2\folder2";
string[] directories = mypath.Split(Path.DirectorySeparatorChar);

편집 : 디렉터리 배열의 각 개별 폴더를 반환합니다. 다음과 같이 반환 된 폴더 수를 얻을 수 있습니다.

int folderCount = directories.Length;

이것은 일반적인 경우에 좋습니다.

yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries)

경로 자체가 (백) 슬래시 (예 : "\ foo \ bar \")로 끝나는 경우 반환 된 배열에 빈 요소가 없습니다. 그러나 yourPath파일이 아니라 실제로 디렉토리 인지 확인해야 합니다. 이것이 무엇인지 알아 내고 다음과 같은 파일 인 경우 보상 할 수 있습니다.

if(Directory.Exists(yourPath)) {
  var entries = yourPath.Split(@"\/", StringSplitOptions.RemoveEmptyEntries);
}
else if(File.Exists(yourPath)) {
  var entries = Path.GetDirectoryName(yourPath).Split(
                    @"\/", StringSplitOptions.RemoveEmptyEntries);
}
else {
  // error handling
}

나는 이것이 너무 현명하지 않고 모든 기반을 포함한다고 믿습니다. 각 디렉토리를 차례로 가져 오기 위해 string[]반복 할 수있는를 반환합니다 foreach.

@"\/"매직 스트링 대신 상수 를 사용하려면 다음을 사용해야합니다.

var separators = new char[] {
  Path.DirectorySeparatorChar,  
  Path.AltDirectorySeparatorChar  
};

그런 다음 위의 코드 separators대신 사용 @"\/"하십시오. 개인적으로 나는 이것이 너무 장황하다고 생각하고 대부분 그렇게하지 않을 것입니다.


이것이 오래된 게시물이라는 것을 깨달았지만 나는 그것을 보았습니다. 결국 나는 위의 어떤 것보다 더 나은 시간에 내가하고 있던 것을 정렬했기 때문에 결국 아래 기능을 결정했습니다.

private static List<DirectoryInfo> SplitDirectory(DirectoryInfo parent)
{
    if (parent == null) return null;
    var rtn = new List<DirectoryInfo>();
    var di = parent;

    while (di.Name != di.Root.Name)
    {
    rtn.Add(new DirectoryInfo(di));
    di = di.Parent;
    }
    rtn.Add(new DirectoryInfo(di.Root));

    rtn.Reverse();
    return rtn;
}

나는 당신의 방법 Wolf5370을 보고 당신 을 키 웁니다 .

internal static List<DirectoryInfo> Split(this DirectoryInfo path)
{
    if(path == null) throw new ArgumentNullException("path");
    var ret = new List<DirectoryInfo>();
    if (path.Parent != null) ret.AddRange(Split(path.Parent));
    ret.Add(path);
    return ret;
}

c:\folder1\folder2\folder3이 반환 경로에서

c:\

c:\folder1

c:\folder1\folder2

c:\folder1\folder2\folder3

그와 같은 순서로

또는

internal static List<string> Split(this DirectoryInfo path)
{
    if(path == null) throw new ArgumentNullException("path");
    var ret = new List<string>();
    if (path.Parent != null) ret.AddRange(Split(path.Parent));
    ret.Add(path.Name);
    return ret;
}

돌아올 것이다

c:\

folder1

folder2

folder3


public static IEnumerable<string> Split(this DirectoryInfo path)
{
    if (path == null) 
        throw new ArgumentNullException("path");
    if (path.Parent != null)
        foreach(var d in Split(path.Parent))
            yield return d;
    yield return path.Name;
}

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    /// <summary>
    /// Use to emulate the C lib function _splitpath()
    /// </summary>
    /// <param name="path">The path to split</param>
    /// <param name="rootpath">optional root if a relative path</param>
    /// <returns>the folders in the path. 
    ///     Item 0 is drive letter with ':' 
    ///     If path is UNC path then item 0 is "\\"
    /// </returns>
    /// <example>
    /// string p1 = @"c:\p1\p2\p3\p4";
    /// string[] ap1 = p1.SplitPath();
    /// // ap1 = {"c:", "p1", "p2", "p3", "p4"}
    /// string p2 = @"\\server\p2\p3\p4";
    /// string[] ap2 = p2.SplitPath();
    /// // ap2 = {@"\\", "server", "p2", "p3", "p4"}
    /// string p3 = @"..\p3\p4";
    /// string root3 = @"c:\p1\p2\";
    /// string[] ap3 = p1.SplitPath(root3);
    /// // ap3 = {"c:", "p1", "p3", "p4"}
    /// </example>
    public static string[] SplitPath(this string path, string rootpath = "")
    {
        string drive;
        string[] astr;
        path = Path.GetFullPath(Path.Combine(rootpath, path));
        if (path[1] == ':')
        {
            drive = path.Substring(0, 2);
            string newpath = path.Substring(2);
            astr = newpath.Split(new[] { Path.DirectorySeparatorChar }
                , StringSplitOptions.RemoveEmptyEntries);
        }
        else
        {
            drive = @"\\";
            astr = path.Split(new[] { Path.DirectorySeparatorChar }
                , StringSplitOptions.RemoveEmptyEntries);
        }
        string[] splitPath = new string[astr.Length + 1];
        splitPath[0] = drive;
        astr.CopyTo(splitPath, 1);
        return splitPath;
    }

빠른 대답은 .Split ( '\\') 메서드를 사용하는 것입니다.


루프에서 Directory.GetParent호출 할 수 있습니까? 디렉토리 이름뿐만 아니라 각 디렉토리의 전체 경로를 원하는 경우입니다.


이전 답변에서 영감을 얻었지만 더 간단하고 재귀가 없습니다. 또한 다음과 같이 구분 기호가 무엇인지 상관하지 않습니다 Dir.Parent.

    /// <summary>
    /// Split a directory in its components.
    /// Input e.g: a/b/c/d.
    /// Output: d, c, b, a.
    /// </summary>
    /// <param name="Dir"></param>
    /// <returns></returns>
    public static IEnumerable<string> DirectorySplit(this DirectoryInfo Dir)
    {
        while (Dir != null)
        {
            yield return Dir.Name;
            Dir = Dir.Parent;
        }
    }

static멋진 확장 메서드를 만들려면 클래스에 이것을 붙이 거나 this(및 static)을 생략하십시오 .

번호로 경로 부분에 액세스하는 사용 예 (확장 방법) :

    /// <summary>
    /// Return one part of the directory path.
    /// Path e.g.: a/b/c/d. PartNr=0 is a, Nr 2 = c.
    /// </summary>
    /// <param name="Dir"></param>
    /// <param name="PartNr"></param>
    /// <returns></returns>
    public static string DirectoryPart(this DirectoryInfo Dir, int PartNr)
    {
        string[] Parts = Dir.DirectorySplit().ToArray();
        int L = Parts.Length;
        return PartNr >= 0 && PartNr < L ? Parts[L - 1 - PartNr] : "";
    }

위의 두 방법 모두 이제 내 개인 라이브러리에 있으므로 xml 주석이 있습니다. 사용 예 :

    DirectoryInfo DI_Data = new DirectoryInfo(@"D:\Hunter\Data\2019\w38\abc\000.d");
    label_Year.Text = DI_Data.DirectoryPart(3); // --> 2019
    label_Entry.Text = DI_Data.DirectoryPart(6);// --> 000.d

파일 경로를 표현할 수있는 몇 가지 방법이 있습니다. System.IO.PathUNIX와 Windows간에 다를 수 있으므로이 클래스를 사용하여 OS의 구분 기호를 가져와야합니다. 또한 대부분의 (또는 내가 잘못하지 않았다면 모두) .NET 라이브러리는 OS에 관계없이 '\'또는 '/'를 경로 구분 기호로 허용합니다. 이러한 이유로 Path 클래스를 사용하여 경로를 분할합니다. 다음과 같이 시도하십시오.

string originalPath = "\\server\\folderName1\\another\ name\\something\\another folder\\";
string[] filesArray = originalPath.Split(Path.AltDirectorySeparatorChar,
                              Path.DirectorySeparatorChar);

이것은 폴더 수나 이름에 관계없이 작동합니다.


또는 각 폴더에 대해 작업을 수행해야하는 경우 System.IO.DirectoryInfo 클래스를 살펴보십시오. 또한 부모 디렉터리로 이동할 수있는 부모 속성이 있습니다.


나는 나를 위해 일하는 다음 방법을 썼다.

protected bool isDirectoryFound(string path, string pattern)
    {
        bool success = false;

        DirectoryInfo directories = new DirectoryInfo(@path);
        DirectoryInfo[] folderList = directories.GetDirectories();

        Regex rx = new Regex(pattern);

        foreach (DirectoryInfo di in folderList)
        {
            if (rx.IsMatch(di.Name))
            {
                success = true;
                break;
            }
        }

        return success;
    }

귀하의 질문에 가장 적합한 라인은 다음과 같습니다.

DirectoryInfo directories = new DirectoryInfo(@path); DirectoryInfo[] folderList = directories.GetDirectories();


DirectoryInfo objDir = new DirectoryInfo(direcotryPath);
DirectoryInfo [] directoryNames =  objDir.GetDirectories("*.*", SearchOption.AllDirectories);

This will give you all the directories and subdirectories.


I am adding to Matt Brunell's answer.

            string[] directories = myStringWithLotsOfFolders.Split(Path.DirectorySeparatorChar);

            string previousEntry = string.Empty;
            if (null != directories)
            {
                foreach (string direc in directories)
                {
                    string newEntry = previousEntry + Path.DirectorySeparatorChar + direc;
                    if (!string.IsNullOrEmpty(newEntry))
                    {
                        if (!newEntry.Equals(Convert.ToString(Path.DirectorySeparatorChar), StringComparison.OrdinalIgnoreCase))
                        {
                            Console.WriteLine(newEntry);
                            previousEntry = newEntry;
                        }
                    }
                }
            }

This should give you:

"\server"

"\server\folderName1"

"\server\folderName1\another name"

"\server\folderName1\another name\something"

"\server\folderName1\another name\something\another folder\"

(or sort your resulting collection by the string.Length of each value.


Here's a modification of Wolf's answer that leaves out the root and fixes what seemed to be a couple of bugs. I used it to generate a breadcrumbs and I didn't want the root showing.

this is an extension of the DirectoryInfo type.

public static List<DirectoryInfo> PathParts(this DirectoryInfo source, string rootPath)
{
  if (source == null) return null;
  DirectoryInfo root = new DirectoryInfo(rootPath);
  var pathParts = new List<DirectoryInfo>();
  var di = source;

  while (di != null && di.FullName != root.FullName)
  {
    pathParts.Add(di);
    di = di.Parent;
  }

  pathParts.Reverse();
  return pathParts;
}

I just coded this since I didn't find any already built in in C#.

/// <summary>
/// get the directory path segments.
/// </summary>
/// <param name="directoryPath">the directory path.</param>
/// <returns>a IEnumerable<string> containing the get directory path segments.</returns>
public IEnumerable<string> GetDirectoryPathSegments(string directoryPath)
{
    if (string.IsNullOrEmpty(directoryPath))
    { throw new Exception($"Invalid Directory: {directoryPath ?? "null"}"); }

    var currentNode = new System.IO.DirectoryInfo(directoryPath);

    var targetRootNode = currentNode.Root;
    if (targetRootNode == null) return new string[] { currentNode.Name };
    var directorySegments = new List<string>();
    while (string.Compare(targetRootNode.FullName, currentNode.FullName, StringComparison.InvariantCultureIgnoreCase) != 0)
    {
        directorySegments.Insert(0, currentNode.Name);
        currentNode = currentNode.Parent;
    }
    directorySegments.Insert(0, currentNode.Name);
    return directorySegments;
}

참고URL : https://stackoverflow.com/questions/401304/how-does-one-extract-each-folder-name-from-a-path

반응형