JefClaes
JefClaes

Reputation: 3373

Get all paths to files in the Content folder in ASP.NET MVC

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

Answers (1)

Darin Dimitrov
Darin Dimitrov

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

Related Questions