Anyname Donotcare Anyname Donotcare - 1 month ago 4
C# Question

How to get files names in multiple folders under some condition

If I have a path like this:

C:\Program Files (x86)\basic\data\


and in this path folders like this :

20160314_002_874
20160314_004_657
20160314_006_169
20160315_006_169
20160316_006_169





How to get all files names in these folders where the date part of these folders names = specific date

Ex :
I want all files names in folders which name begin with the following date(
20160314
)in a list.

Answer

Use DirectoryInfo:

using System.Collections.Generic;
using System.IO;

List<FileInfo> files = new List<FileInfo>();
DirectoryInfo rootDir = new DirectoryInfo(@"C:\Program Files (x86)\basic\data\");
var directories = rootDir.GetDirectories("20160314*");
foreach (var directory in directories)
{
    files.AddRange(directory.GetFiles());
}

IEnumerable<string> fileNames = files.Select(f => f.Name);

use IEnumerable<string> fileNames = files.Select(f => f.FullName); to get the file name with path.

Comments