[英]C# read folder (names) from directory
I have this code: 我有这个代码:
string directory;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
directory = fbd.SelectedPath;
txtSource.Text = directory;
DirectoryInfo d = new DirectoryInfo(directory);
FileInfo[] Files = d.GetFiles();
List<String> str = new List<string>();
foreach (FileInfo file in Files)
{
str.Add(file.Name);
}
}
I have a FolderBrowseDialog
where I select the Path of the folder. 我有一个
FolderBrowseDialog
,我在其中选择文件夹的路径。 In this selected folder are 3 other folders. 在此选定文件夹中有3个其他文件夹。 I want to read out the names of these folders.
我想读出这些文件夹的名称。 I dont want to know or read out the names of files.
我不想知道或读出文件的名称。
You can use Directory.GetDirectories()
: 您可以使用
Directory.GetDirectories()
:
string[] subdirs = Directory.GetDirectories(fbd.SelectedPath);
This gives you the full paths to the subdirectories. 这为您提供了子目录的完整路径。 If you only need the names of the subfolders, but not the full path, you can use
Path.GetFileName()
: 如果您只需要子文件夹的名称,而不是完整路径,则可以使用
Path.GetFileName()
:
string[] subdirs = Directory.GetDirectories(fbd.SelectedPath)
.Select(Path.GetFileName)
.ToArray();
Or if you want both: 或者如果你想要两个:
var subdirs = Directory.GetDirectories(fbd.SelectedPath)
.Select(p => new {
Path = p,
Name = Path.GetFileName(p)})
.ToArray();
You need to use DirectoryInfo.GetDirectories . 您需要使用DirectoryInfo.GetDirectories 。
using System;
using System.IO;
public class GetDirectoriesTest
{
public static void Main()
{
// Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo("c:\\");
// Get a reference to each directory in that directory.
DirectoryInfo[] diArr = di.GetDirectories();
// Display the names of the directories.
foreach (DirectoryInfo dri in diArr)
Console.WriteLine(dri.Name);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.