我需要列出Content文件夹中文件的所有相对路径。
我写了一些有用的东西,但它看起来有点脆弱。是否有更好/更聪明的方法来做到这一点?
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;
}
答案 0 :(得分:3)
以下似乎更短:
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, ""))
);
}
另请注意,我使用Directory.EnumerateFiles
代替Directory.GetFiles
。此方法是在.NET 4.0中引入的,并返回IEnumreable<string>
而不是string[]
。这样做的好处是显而易见的。在内部,此方法使用FindFirstFile和FindNextFile Win32函数。这意味着只有在开始枚举结果集时才会执行实际的文件系统搜索。