访问子目录中的文件

时间:2018-11-16 17:37:06

标签: c#

我正在尝试访问位于另一个目录中的images目录中的文件,但是当我运行代码时,它不会打印出任何内容:

string path = @"C:\Path";
DirectoryInfo DFolder = new DirectoryInfo(path);
Collection cDetails = new Collection(DFolder);
string DFPath = DFolder.Name;

DirectoryInfo imDetails = new DirectoryInfo(imPath);

// Get Desired Directories    
List<string> directoryFilter = new List<string> {"images", "videos", "RAW"};

List<DirectoryInfo> directoryList = DFolder
    .GetDirectories("*", SearchOption.AllDirectories)
    .Where(x => directoryFilter.Contains(x.Name.ToLower()))
    .ToList();

string dpath = directoryList.ToString();

foreach (DirectoryInfo record in directoryList)
{
    foreach (FileInfo file in record.GetFiles(@"*", SearchOption.TopDirectoryOnly))
    {
        Console.WriteLine(file); //It compiles but doesn't print anything on the console
    }
}   

2 个答案:

答案 0 :(得分:0)

注意:这并不是真正的答案,因此我将很快将其删除,但希望提供一些示例代码进行测试,以防它有所帮助。

您的代码对我来说很好,所以看来问题出在目录不存在,或者它们不包含任何文件。

这是您可以运行的测试程序,该程序在c:\temp下创建一堆目录,其中一些目录具有我们关心的名称。我们关心的名称也可以在路径的不同深度找到,但都可以找到:

static void CreateTestPathsAndFiles()
{
    // Paths to create for testing. We will put a file in each directory below,
    // but our search code should only print the file paths of those files that
    // are directly contained in one of our specially-named folders
    var testPaths = new List<string>
    {
        @"c:\temp\dummy1",
        @"c:\temp\dummy1\raw",         // This should print
        @"c:\temp\dummy2",
        @"c:\temp\dummy2\extra",
        @"c:\temp\dummy3",
        @"c:\temp\dummy3\dummy31",
        @"c:\temp\dummy3\dummy32\raw", // This should print
        @"c:\temp\extra",
        @"c:\temp\images",             // This should print
        @"c:\temp\notUsed",
        @"c:\temp\notUsed\videos",     // This should print
        @"c:\temp\raw",                // This should print
        @"c:\temp\videos\dummy1",
    };

    // Just something to make a unique file name
    int fileId = 0;

    // for testing, ensure that the directories exist and contain some files
    foreach(var testPath in testPaths)
    {
        // Create the directory
        Directory.CreateDirectory(testPath);

        // Add a file to it
        File.CreateText(Path.Combine(testPath, $"TempFile{fileId}.txt"))
            .Write($"Dummy text in file {fileId}");

        // Increment our file counter
        fileId++;
    }
}

static void Main(string[] args)
{
    // Create our paths and files for testing
    CreateTestPathsAndFiles();

    // Now set our root directory, search for all folders matching our 
    // special folder names, and print out the files contained in them
    var path = @"C:\Temp";
    var directoryFilter = new List<string> {"images", "videos", "raw"};

    // Get ALL sub-directories under 'path' whose name is in directoryFilter
    var subDirectories = new DirectoryInfo(path)
        .GetDirectories("*", SearchOption.AllDirectories)
        .Where(x => directoryFilter.Contains(x.Name.ToLower()));

    foreach (DirectoryInfo subDir in subDirectories)
    {
        foreach (FileInfo file in subDir.GetFiles(@"*", SearchOption.TopDirectoryOnly))
        {
            // We're using the FullName so we see the whole file path in the output
            Console.WriteLine(file.FullName);
        }
    }

    GetKeyFromUser("\nDone! Press any key to exit...");
}

输出

请注意,列出了我们希望找到的5个文件,但没有列出其他文件:

enter image description here

答案 1 :(得分:-1)

 foreach (FileInfo file in record.GetFiles(@"*", SearchOption.TopDirectoryOnly))
{
    Console.WriteLine(file); //It compiles but doesn't print anything on the console
}

SearchOption.TopDirectoryOnly仅搜索C://Path/images中的文件,而不搜索其子文件夹。

对此的一种可能的解决方法是,只需将您的第二个foreach循环更改为如下所示:

foreach (FileInfo file in record.GetFiles(@"*", SearchOption.AllDirectories))
{
    Console.WriteLine(file); //It compiles but doesn't print anything on the console
}

修改:

使用SearchOption.AllDirectories作为参数应该可以捕获子文件夹中所有子文件夹的情况,例如类似于C://images//dir//somefile.txt,而不是仅获取顶层目录(在这种情况下为C://images)中的文件。 (据我所知,这正是您所寻找的行为)。 完整代码:

{

    static void Main(string[] args)
  { 
    // Directory Info
    string path = @"C:\Path";
    DirectoryInfo DFolder = new DirectoryInfo(path);
    string DFPath = DFolder.Name;


    // Get Desired Directories

    List<string> directoryFilter = new List<string> { "images", "videos", "raw" };

    List<DirectoryInfo> directoryList = DFolder.GetDirectories("*", SearchOption.AllDirectories).Where(x => directoryFilter.Contains(x.Name.ToLower())).ToList(); 

    string dpath = directoryList.ToString();

    foreach (DirectoryInfo record in directoryList)
    {

        foreach (FileInfo file in record.GetFiles(@"*", SearchOption.AllDirectories)) //searches directory record and its subdirectories
        {
            Console.WriteLine(file); 
        }

    }
}

最终编辑:示例输出具有以下结构:

C://Path//images//images.somefile.txt
C://Path//images//temp//images.temp.somefile.txt
C://Path//raw//raw.somefile.txt
C://Path//vidoes//videos.somefile.txt

enter image description here