c#を使用してハードドライブ上のすべてのディレクトリ(サブディレクトリを含む)を取得するにはどうすればよいですか?
応答の例:
C:\
C:\1
C:\2
C:\2\1
C:\2\1\4
C:\2\1\4\5
C:\2\1\4\5\6
C:\3
c#を使用してハードドライブ上のすべてのディレクトリ(サブディレクトリを含む)を取得するにはどうすればよいですか?
応答の例:
C:\
C:\1
C:\2
C:\2\1
C:\2\1\4
C:\2\1\4\5
C:\2\1\4\5\6
C:\3
using System.IO;
var directories = new List<string>(Directory.GetDirectories(@"c:\", "*", SearchOption.AllDirectories));
directories.ForEach(directory => Console.WriteLine(directory));
ジャスティンの答えは 100% うまくいきます。これが結果を得ることよりも技術を学ぶことに関するものである場合、再帰関数が必要になります。つまり、返された結果に対して自分自身を呼び出す関数が必要です。
public static void GetDirectories(string path, bool recursive)
{
Console.WriteLine(path); // write the name of the current directory
if (recursive) // if we want to get subdirectories
{
try // getting directories will throw an error if it is a path you don't have access to
{
foreach (var child in Directory.GetDirectories(path)) // get all the subdirectories for the given path
{
GetDirectories(child, recursive); // call our function for each sub directory
}
}
catch (UnauthorizedAccessException ex) // handle unauthorized access errors
{
Console.WriteLine(string.Format("You don't have permission to view subdirectories of {0}",path));
}
}
}
そして、それを呼び出すには:
static void Main(string[] args)
{
GetDirectories("c:\\", true);
Console.ReadLine();
}
繰り返しますが、リストを取得しようとしているだけの場合は、ジャスティンの答えを使用してください。ただし、これは自分で行う方法です。