-1

in my local file folder,contain files. eg TB2.8.5_asd_asd and TB2.9.5_asd_asd. How can i do only get the file which the name start with TB2.6.5_

string[] dirs = System.IO.Directory.GetFiles(ConfigurationManager.AppSettings[@"LocalFolderPath"], "*" + ConfigurationManager.AppSettings["LocalFilesExtension"]).Where(s => s.StartsWith("TB2.6.5_")).ToArray();
Yeep
  • 43
  • 1
  • 2
  • 11

2 Answers2

3

The Directory.GetFiles() method allows you to specify the search pattern as one of its input parameters. you can utilize that to complete your requirement. So the code will be like this:

string PathToDirectory=Path.Combine(ConfigurationManager.AppSettings[@"LocalFolderPath"], ConfigurationManager.AppSettings[@"LocalFilesExtension"];
string searchPattern="TB2.6.5_*.*";
string[] dirs =  System.IO.Directory.GetFiles(PathToDirectory,searchPattern,SearchOption.TopDirectoryOnly).ToArray();

Change SearchOption to AllDirectories if you want to extend the search to sub-directories, You can change the searchPattern according to the requirement.

Update as per your comment: Illegal characters in path.

This will be depend on the value you are storing in the config. ie., AppSettings["LocalFilesExtension"] if there is \\ used as path separator, then need not to include @ before i\since it will convert the \\ to \\\\ If There is only a single \ in Config then use @

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
  • Illegal characters in path. – Yeep Jun 29 '16 at 06:44
  • string PathToDirectory="ConfigurationManager.AppSettings[@'LocalFolderPath'], '*' + ConfigurationManager.AppSettings['LocalFilesExtension']"; string[] dirs = System.IO.Directory.GetFiles(PathToDirectory, "TB2.6.5_*.*", System.IO.SearchOption.AllDirectories).ToArray(); – Yeep Jun 29 '16 at 06:44
  • @Yeep: The reason for this will be the data you stored in the config, see the update notes – sujith karivelil Jun 29 '16 at 06:52
  • @Yeep : so use `string PathToDirectory=Path.Combine(ConfigurationManager.AppSettings[@"LocalFolderPath"], ConfigurationManager.AppSettings[@"LocalFilesExtension"];` – sujith karivelil Jun 29 '16 at 07:38
2

You can use the filter parameter to set it

Directory.GetFiles(String, String)

i.e.

"filename.exe" = filters for filename.exe
"filename.*" = filters all files with the name filename
"*filename*" = contains filename
Jan Wiesemann
  • 455
  • 2
  • 16