To get all items in a given current directory it needs to use a combination of two methods: GetDirectories(), GetFiles(). Both of them are the static method in class Directory which return all folders, and all files in the given directory respectively.
static String[] Dir(String path)
{
// Get all folders in a given path
List list = Directory.GetDirectories(path).ToList();
// Get all files in a given path then add them to the list which contains folders
list.AddRange(Directory.GetFiles(path));
// You may sort the result, the ordering will be similar to dir function in the command prompt
list.Sort();
// Get the result
return list.ToArray();
}
To use the function you written, it is very easy to use by giving the string path to it, it will give you an result.
static void Main(string[] args)
{
string[] filepaths = Dir(@"C:\\");
// Show all items under your drive C.
foreach (String filepath in filepaths)
Console.WriteLine(filepath);
}
No comments:
Post a Comment