freethinker
freethinker

Reputation: 2425

Get files from directory by dynamic path

I want to get files from a directory, and I have the directory's path in my configuration file. If I get files names like this:

var filePaths = Directory.GetFiles(@"SomePath", "*.*",
  SearchOption.AllDirectories).ToList();

So all work perfect. But if I try to get fileNames like this:

var path = ConfigurationManager.AppSettings.GetValues("Key");
var filePaths = Directory.GetFiles(path[0], "*.*",
  SearchOption.AllDirectories).ToList();

I get an empty list. I think the problem is in the syntax of @ before the string path. But how can I give the @ before the path into the string path[0]?

Thanks.

Upvotes: 0

Views: 4068

Answers (2)

Prashanth Thurairatnam
Prashanth Thurairatnam

Reputation: 4361

Read more on verbatim strings. These are denoted with a leading @ sign followed with the string within double quotes, where the string does not need escape sequence for special characters. For example @"c:\Docs\Source" is same as "c:\\Docs\\Source"

In your case make sure path[0] is in "c:\\Docs\\Source" format

Upvotes: 1

Amiram Korach
Amiram Korach

Reputation: 13286

You can add a backslash before an existing one:

var filePaths = Directory.GetFiles(path[0].Replace("\\", "\\\\"), "*.*", SearchOption.AllDirectories).ToList();

Upvotes: 0

Related Questions