Skip to content

Instantly share code, notes, and snippets.

@poychang
Last active May 1, 2019 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poychang/e3c914c1a58d0848d9e33d9d4b004ef4 to your computer and use it in GitHub Desktop.
Save poychang/e3c914c1a58d0848d9e33d9d4b004ef4 to your computer and use it in GitHub Desktop.
[取得指定往下第幾層的資料夾路徑] 只取指定層數的資料夾路徑,避免子資料夾路徑太深、太多造成效能問題 #dotnet
using System.IO;
using System.Collections.Generic;
/// <summary>
/// 取得指定往下第幾層的資料夾路徑
/// </summary>
/// <remarks>使用此方法只取指定層數的資料夾路徑,避免子資料夾路徑太深、太多造成效能問題</remarks>
/// <param name="path">根路徑</param>
/// <param name="depth">第幾層的資料夾路徑</param>
/// <returns></returns>
public static IEnumerable<string> EnumerateSubDirectories(string path, int depth)
{
if (!Directory.Exists(path)) return new List<string>();
var result = new List<string>();
depth--;
foreach (var subPath in Directory.EnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly))
{
result.AddRange(depth == 0 ? new List<string> { subPath } : EnumerateSubDirectories(subPath, depth));
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment