I really prefer to pass the parameter of the function to a method that does what I want. I have a SearchDirectory method that forms the basis for most of the calls that I use:
private void SearchDirectory(DirectoryInfo startDirectory, string pattern, Action<FileInfo> act) { foreach (var file in startDirectory.GetFiles(pattern)) act(file); foreach (var directory in startDirectory.GetDirectories()) SearchDirectory(directory, pattern, act); } private List<FileInfo> SearchDirectory(DirectoryInfo startDirectory, string pattern, Func<FileInfo, bool> isWanted) { var lst = new List<FileInfo>(); SearchDirectory(startDirectory, pattern, (fi) => { if (isWanted(fi)) lst.Add(fi); }); return lst; }
Then you can use the other solutions listed to write the IsHidden function, which takes one FileInfo and returns true if it is:
private bool IsHiddenDirectory(DirectoryInfo d) { if (d == null) return false; if (d.Attributes.HasFlag(FileAttributes.Hidden))) return true; if (d.Parent == null) return false; return IsHiddenDirectory(d.Parent); } private bool IsHidden(FileInfo fi) { if ((fi.Attributes & FileAttributes.Hidden) != 0) return true;
Then I can call it another way quite easily:
var files = SearchDirectory(new DirectoryInfo("C:\temp\"), "*.xml", (fi) => { return !IsHidden(fi); );
Jonathan Nov 08 '16 at 13:09 2016-11-08 13:09
source share