Reputation: 49
I want to know which folder contains files which have a $
in their names.
But I will get duplicate folder names if I use this code:
string local = @"C:\test\";
string[] dirs = Directory.GetFiles(local, "*$*", SearchOption.AllDirectories);
foreach(string dir in dirs)
{
string a = Path.GetFileName(Path.GetDirectoryName(dir));
}
This is the content of the test folder:
- C:\test\20170321\$123.txt
- C:\test\20170321\2$4.txt
- C:\test\20170322\567.txt
- C:\test\20170322\abc.txt
should be get result only 1 20170321
Upvotes: 1
Views: 3729
Reputation: 23732
This should do it:
string local = @"C:\test\";
string[] dirs = Directory.GetFiles(local, "*$*", SearchOption.AllDirectories);
List<string> singleDirNames = dirs.Select(x=> Path.GetDirectoryName(x)).Distinct().ToList();
Explanation: Select from all filenames the directory and take only the distinct values of it into a list
EDIT:
As I just realized, you don't want the entire path, so to get the result from your post you need to use the Path.GetFileName()
(there should be another way, I am looking for it):
List<string> singleDirNames = dirs
.Select(x=> Path.GetFileName(Path.GetDirectoryName(x)))
.Distinct().ToList();
Found it. Here would be actually the direct way to access the containing folder inspired by this answer:
List<string> singleDirNames = dirs.Select(x=> new FileInfo(x).Directory.Name)
.Distinct().ToList();
Upvotes: 4