我有以下代码,当用户将其放在我的C#Winforms应用程序窗口上的按钮上时,它将处理该文件夹中的文件夹和文件。这段代码工作正常:
List<string> filepaths = new List<string>();
foreach (var s in (string[])e.Data.GetData(DataFormats.FileDrop, false))
{
if (Directory.Exists(s))
{
//Add files from folder
filepaths.AddRange(Directory.GetFiles(s));
}
else
{
//Add filepath
filepaths.Add(s);
}
}
但是,如果主文件夹(子文件夹)中有另一个文件夹,则它不会检测到该子文件夹并列出子文件夹中的文件。
有人可以告诉我如何检测子文件夹的名称以及子文件夹中的文件吗?
编辑:这样的事情会起作用吗?
string[] fileList = Directory.GetFiles(@s, "*.*", SearchOption.AllDirectories);
答案 0 :(得分:1)
你需要使用Directory.GetDirectories()来拉回子目录,然后循环遍历它们,类似于你现在正在做的事情。
// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string [] fileEntries = Directory.GetFiles(targetDirectory);
foreach(string fileName in fileEntries)
ProcessFile(fileName);
// Recurse into subdirectories of this directory.
string [] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach(string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
来源:MSDN
答案 1 :(得分:1)
与Frazell类似,但我喜欢使用文件和目录信息类型,如:
编辑:添加了ProcessFile()方法
public void ProcessFolder(DirectoryInfo dirInfo)
{
//Check for sub Directories
foreach (DirectoryInfo di in dirInfo.GetDirectories())
{
//Call itself to process any sub directories
ProcessFolder(di);
}
//Process Files in Directory
foreach (FileInfo fi in dirInfo.GetFiles())
{
//Do something with the file here
//or create a method like:
ProcessFile(fi)
}
}
public void ProcessFile(FileInfo fi)
{
//Do something with your file
Debug.Print(fi.FullName);
//...
}