1

我有以下代码,当用户将其放到我的 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);
4

2 回答 2

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

于 2012-12-20T19:35:31.573 回答
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);
    //...
}
于 2012-12-20T20:18:31.667 回答