在C#中,如何检查目录或其任何子目录中是否存在特定文件?
System.IO.File.Exists似乎只接受一个没有重载的单个参数来搜索子目录.
我可以使用SearchOption.AllDirectories重载LINQ和System.IO.Directory.GetFiles,但这看起来有点沉重.
var MyList = from f in Directory.GetFiles(tempScanStorage, "foo.txt", SearchOption.AllDirectories)
where System.IO.Path.GetFileName(f).ToUpper().Contains(foo)
select f;
foreach (var x in MyList)
{
returnVal = x.ToString();
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 39
如果你正在寻找一个特定的文件名,那么使用*.*确实很重要.试试这个:
var file = Directory.GetFiles(tempScanStorage, foo, SearchOption.AllDirectories)
.FirstOrDefault();
if (file == null)
{
// Handle the file not being found
}
else
{
// The file variable has the *first* occurrence of that filename
}
Run Code Online (Sandbox Code Playgroud)
请注意,这不是您当前查询所做的 - 因为如果您只是foo,那么您当前的查询会找到"xbary.txt" bar.我不知道这是否有意.
如果你想知道多个匹配,你FirstOrDefault()当然不应该使用.目前尚不清楚你正在尝试做什么,这使得很难给出更具体的建议.
请注意,在.NET 4中,还有Directory.EnumerateFiles哪些可能会或可能不会更好地为您执行.我非常怀疑当你搜索一个特定的文件(而不是目录和子目录中的所有文件)时它会有所作为,但它至少值得了解.编辑:如评论中所述,如果您没有权限查看目录中的所有文件,则可能会有所不同.
The alternative is to write the search function yourself, one of these should work:
private bool FileExists(string rootpath, string filename)
{
if(File.Exists(Path.Combine(rootpath, filename)))
return true;
foreach(string subDir in Directory.GetDirectories(rootpath, "*", SearchOption.AllDirectories))
{
if(File.Exists(Path.Combine(subDir, filename)))
return true;
}
return false;
}
private bool FileExistsRecursive(string rootPath, string filename)
{
if(File.Exists(Path.Combine(rootPath, filename)))
return true;
foreach (string subDir in Directory.GetDirectories(rootPath))
{
return FileExistsRecursive(subDir, filename);
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
The first method still extracts all of the directory names and would be slower when there many subdirs but the file is close to the top.
The second is recursive which would be slower in 'worst case' scenarios but faster when there are many nested subdirs but the file is in a top level dir.
| 归档时间: |
|
| 查看次数: |
74004 次 |
| 最近记录: |