gpt4 book ai didi

c# 在路径未知时查找文件夹然后列出文件并返回

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:25 25 4
gpt4 key购买 nike

我正在学习c#,需要在不知道完整路径的情况下找到一个文件夹。例如,您知道专辑名称但不知道音乐文件夹中的艺术家。查找相册名称不是此代码的最终用法,而是此问题的最佳示例。我正在通过递归和限制搜索的深度来做到这一点。一切都很好,除非我找到文件夹并列出我希望它停止并返回的文件,但事实并非如此,即使在我拥有该文件夹之后,它也只是保持递归。我也一直在努力处理异常处理,例如如果权限无效如何跳过文件夹。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace listFoldersTest
{
class Program
{
static void Main(string[] args)
{
Console.SetWindowSize(100, 50);
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\username\Music");
getDirsFiles(dir, 0, 2);
Console.ReadKey();
Console.WriteLine("done");
}
public static void getDirsFiles(DirectoryInfo d, int currentDepth, int maxDepth)
{
String folderToFindName = ("albumName");
bool foundIt = false;

if (currentDepth < maxDepth)
{
DirectoryInfo[] dirs = d.GetDirectories("*.*");
foreach (DirectoryInfo dir in dirs)
{
String pathName = (dir.FullName);
Console.WriteLine("\r{0} ", dir.Name);
if (currentDepth == (maxDepth - 1))
{
if (pathName.IndexOf(folderToFindName) != -1)
{
foundIt = true;
FileInfo[] files = dir.GetFiles("*.*");
foreach (FileInfo file in files)
{
Console.WriteLine("-------------------->> {0} ", file.Name);
} //end foreach files

} // end if pathName

} // end if of get files current depth

if (foundIt == true)
{
return;
}
getDirsFiles(dir, currentDepth + 1, maxDepth);

} //end if foreach directories

} //end if directories current depth

} // end getDirsFiles function
}
}

最佳答案

using System;
using System.IO;

namespace listFoldersTest
{
class Program
{
private static bool foundIt;

static void Main(string[] args)
{
Console.SetWindowSize(100, 50);
try
{
DirectoryInfo dir = new DirectoryInfo(args[0]);
getDirsFiles(dir, 0, 2);
}
catch
{
}
Console.ReadKey();
Console.WriteLine("done");
}

public static void getDirsFiles(DirectoryInfo d, int currentDepth, int maxDepth)
{
if(d == null || foundIt) return;
String folderToFindName = ("albumName");
if (currentDepth < maxDepth)
{
DirectoryInfo[] dirs = d.GetDirectories("*.*");
foreach (DirectoryInfo dir in dirs)
{
String pathName = (dir.FullName);
Console.WriteLine("\r{0} ", dir.Name);
if (currentDepth == (maxDepth - 1))
{
if (pathName.IndexOf(folderToFindName) != -1)
{
foundIt = true;
FileInfo[] files = dir.GetFiles("*.*");
foreach (FileInfo file in files)
{
Console.WriteLine("-------------------->> {0} ", file.Name);
} //end foreach files
return;
} // end if pathName
} // end if of get files current depth
getDirsFiles(dir, currentDepth + 1, maxDepth);
} //end if foreach directories
} //end if directories current depth
} // end getDirsFiles function
}
}

关于c# 在路径未知时查找文件夹然后列出文件并返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7760725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com