我试图通过递归搜索任意目录来返回FileInfo类型的列表。但是,在我的main()方法中,当我检查以查看FoundFiles的计数时,它为0表示我返回了一个空对象。请参阅以下代码:
using System;
using System.IO;
using System.Collections.Generic;
class FindExtensions
{
private static List<FileInfo> SearchFileSystem(DirectoryInfo DirInfo, List<FileInfo> FileList)
{
List<FileInfo> FileInfoList = new List<FileInfo>();
try
{
foreach (DirectoryInfo SubdirInfo in DirInfo.GetDirectories())
{
SearchFileSystem(SubdirInfo, FileList);
}
}
catch
{
// do some stuff
}
try
{
foreach (FileInfo File in DirInfo.GetFiles())
{
FileInfoList.Add(File);
}
}
catch
{
// do some stuff
}
foreach (FileInfo f in FileInfoList)
{
Console.WriteLine(f.FullName);
}
return FileInfoList;
}
static void Main()
{
DirectoryInfo dir_info = new DirectoryInfo(@"C:\<whatever>");
List<FileInfo> file_list = new List<FileInfo>();
List<FileInfo> FoundFiles = SearchFileSystem(dir_info, file_list);
Console.WriteLine("Count is: " + FoundFiles.Count);
//^^^^ this returns 0...why is it empty?
Console.WriteLine("This is the debug mode. Press key to restart");
Console.ReadKey();
}
}
我在SearchFileSystem方法中添加了一个for循环,以便在返回之前检查FileInfoList的内容,它将包含文件。但是,它主要包含任何内容。我对C#的细微差别感到陌生,所以如果这很容易就道歉。
此外,值得注意的是,如果我使用类型List与字符串而不是FileInfo,这可以正常工作。希望尽可能使用FileInfo类型的List。
感谢。
答案 0 :(得分:2)
您没有添加递归调用的结果。理想情况下,您只从最后一个可能没有某些文件的目录中获取结果。试试这个:
foreach (DirectoryInfo SubdirInfo in DirInfo.GetDirectories())
{
FileInfoList.AddRange(SearchFileSystem(SubdirInfo, FileList));
}
答案 1 :(得分:1)
为什么不使用GetFiles()
方法让它为您完成工作
static void Main()
{
DirectoryInfo dir_info = new DirectoryInfo(@"C:\<whatever>");
List<FileInfo> file_list = new List<FileInfo>();
//This will add all the files in all directories. You can customize the search from here as well.
file_list.AddRange(dir_info.GetFiles("*", SearchOption.AllDirectories));
Console.WriteLine("Count is: " + file_list.Count);
//^^^^ this returns 0...why is it empty?
Console.WriteLine("This is the debug mode. Press key to restart");
Console.ReadKey();
}
但是!在回答您的问题时,您每次致电List<FileInfo> FoundFiles = new List<FileInfo>();
时都会致电SearchFileSystem(...)
。然后你递归地调用该方法,但不要使用那里的任何结果。
如果您想使用现有代码,请执行以下必要的更改:
private static void SearchFileSystem(DirectoryInfo DirInfo, List<FileInfo> FileList)
{
try
{
foreach (DirectoryInfo SubdirInfo in DirInfo.GetDirectories())
{
SearchFileSystem(SubdirInfo, FileList);
}
}
catch
{
// do some stuff
}
//Since we are passing in FileList, let's use it instead of a new list.
try
{
foreach (FileInfo File in DirInfo.GetFiles())
{
FileList.Add(File);
}
}
catch
{
// do some stuff
}
foreach (FileInfo f in FileList)
{
Console.WriteLine(f.FullName);
}
}
static void Main()
{
DirectoryInfo dir_info = new DirectoryInfo(@"C:\<whatever>");
List<FileInfo> file_list = new List<FileInfo>();
SearchFileSystem(dir_info, file_list);
Console.WriteLine("Count is: " + FoundFiles.Count);
//^^^^ this returns 0...why is it empty?
Console.WriteLine("This is the debug mode. Press key to restart");
Console.ReadKey();
}