Reputation: 3373
I need to list all relative paths to files in my Content folder.
I wrote something that works, but it seems a bit brittle. Is there a better/smarter way to do this?
var contentPaths = GetRelativePathsToRoot("~/Content/").ToList();
private IEnumerable<string> GetRelativePathsToRoot(string virtualPath)
{
var physicalPath = Server.MapPath(virtualPath);
var absolutePaths = Directory.GetFiles(physicalPath, "*.*", SearchOption.AllDirectories);
var relativePaths = new List<string>();
foreach (var absolutePath in absolutePaths)
{
var splittedPath = virtualPath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
var virtualFolderName = splittedPath[splittedPath.Length -1];
var relativePath = absolutePath
.Substring(absolutePath.IndexOf(virtualFolderName))
.Replace("\\", "/");
relativePaths.Add(Url.Content("~/" + relativePath));
}
return relativePaths;
}
Upvotes: 2
Views: 2470
Reputation: 1039438
The following seems shorter:
private IEnumerable<string> GetRelativePathsToRoot(string virtualPath)
{
var physicalPath = Server.MapPath(virtualPath);
var absolutePaths = Directory.EnumerateFiles(
physicalPath,
"*.*",
SearchOption.AllDirectories
);
return absolutePaths.Select(
x => Url.Content(virtualPath + x.Replace(physicalPath, ""))
);
}
Also notice that I am using Directory.EnumerateFiles
instead of Directory.GetFiles
. This method was introduced in .NET 4.0 and returns an IEnumreable<string>
instead of a string[]
. The benefits of this are more than obvious. Internally this method uses the FindFirstFile and FindNextFile Win32 functions. This means that the actual file system search is performed only when you start enumerating over the resultset.
Upvotes: 3