我刚刚完成了这个递归方法:
/// <summary>
/// Recursively process a given directory and add its file to Library.xml
/// </summary>
/// <param name="sourceDir">Source directory</param>
public void ProcessDir(string sourceDir)
{
string[] fileEntries = Directory.GetFiles(sourceDir, "*.mp3");
foreach (string fileName in fileEntries)
{
Song newSong = new Song();
newSong.ArtistName = "test artist";
newSong.AlbumName = "test album";
newSong.Name = "test song title";
newSong.Length = 1234;
newSong.FileName = fileName;
songsCollection.Songs.Add(newSong);
}
string[] subdirEntries = Directory.GetDirectories(sourceDir);
foreach (string subdir in subdirEntries)
{
if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
ProcessDir(subdir);
}
}
}一切都像预期的那样工作,我唯一的问题是:我怎么知道这个方法什么时候完成执行?在.NET中有没有专门为这个目的而设计的东西呢?
发布于 2011-02-09 02:00:24
在.NET中没有什么特别的东西可以告诉你这一点。基本上,对ProcessDir的第一个调用将在递归结束后返回。
发布于 2011-02-09 02:03:41
那么,您可以在初始ProcessDir调用之后放置一行代码来指示执行的结束:
ProcessDir("MyDir");
Console.WriteLine("Done!");发布于 2011-02-09 02:09:04
您可以尝试使用全局变量来跟踪它。
private int _processDirTrack = 0;
public void ProcessDir(string sourceDir)
{
_processDirTrack++; // Increment at the start of each
string[] fileEntries = Directory.GetFiles(sourceDir, "*.mp3");
foreach (string fileName in fileEntries)
{
Song newSong = new Song();
newSong.ArtistName = "test artist";
newSong.AlbumName = "test album";
newSong.Name = "test song title";
newSong.Length = 1234;
newSong.FileName = fileName;
songsCollection.Songs.Add(newSong);
}
string[] subdirEntries = Directory.GetDirectories(sourceDir);
foreach (string subdir in subdirEntries)
{
if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
ProcessDir(subdir);
}
}
_processDirTrack--; // Decrement after the recursion. Fall through means it got to
// the end of a branch
if(_processDirTrack == 0)
{
Console.WriteLine("I've finished with all of them.");
}
}https://stackoverflow.com/questions/4936539
复制相似问题