Reputation: 41
I have an array of files, but the problem is the root path isn't attached to the file, so using the data below, how would I go about appending the linq item to the static string?
string rootPath = "C:\\Users\\MyUserName";
List<string> files = new List<string>();
files.Add("\\My Documents\\File1.txt");
files.Add("\\My Documents\\File2.txt");
I essentially want a list that is Path.Combine(rootPath, x); I tried this but no luck:
var fileList = (from x in files
select Path.Combine(rootPath, x)).ToList();
But it doesn't append the rootPath, fileList is the same as the files list.
Any ideas?
Upvotes: 4
Views: 1287
Reputation:
the query works fine if you change
"\\My Documents\\File1.txt" to @"My Documents\\File1.txt"
.
The reason is being described in the post mentioned by Donut.
Hence,
string rootPath = "C:\\Users\\MyUserName";
List<string> files = new List<string>();
files.Add(@"My Documents\\File1.txt");
files.Add(@"My Documents\\File2.txt");
var fileList = (from x in files select Path.Combine(rootPath, x)).ToList();
OR
var fileList = files.Select(i => Path.Combine(rootPath, i));
works fine.
If at all you donot want to change the existing source , then instead of Path.Combine use string.Concat
e.g.
string rootPath = "C:\\Users\\MyUserName";
List<string> files = new List<string>();
files.Add("\\My Documents\\File1.txt");
files.Add("\\My Documents\\File2.txt");
var fileList = (from x in files select string.Concat(rootPath, x)).ToList();
OR
var fileList = files.Select(i => string.Concat(rootPath, i));
Hope this helps
Upvotes: 0
Reputation: 112855
Apparently Path.Combine
will ignore the first parameter if the second parameter has a leading "\
" (this blog entry has some more info).
This should work, it uses Path.Combine
and the ?
operator to account for leading slashes in the second parameter:
var fileList = (from f in files
select Path.Combine(rootPath,
f.StartsWith("\\") ? f.Substring(1) : f)).ToList();
Upvotes: 4