我想在无序列表中列出文件名(在本例中为文章),但是在获取文件的绝对路径时遇到了问题。如何获得可靠且符合标准的解决方案,以在ASP .NET Core中列出解决方案文件名?
我尝试调用Directory.EnumerateFiles(目录路径参数中是否包含〜)
我还尝试过使用GetFiles,在路径错误上得到类似的结果。
我的代码如下:
<p>
<ul>
@foreach (string articulo in Directory.EnumerateFiles("~/Views/Articulo"))
{
<li>
<a asp-controller="Articulo" asp-action="@articulo">@articulo</a>
</li>
}
</ul>
</p>
目前,解决方案上的DOM如下:
-Root Application
-Views
-Articulo
-Todo.cshtml //Only page in the folder
我希望尝试使用正确的锚标记时会出现一些错误,但是却收到了路径错误:
'Directory.EnumerateFiles("~/Views/Articulo")' threw an exception of type 'System.IO.DirectoryNotFoundException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147024893
HelpLink: null
InnerException: null
Message: "Could not find a part of the path 'C:\\Users\\MyUser\\Documents\\Source\\Repos\\MyRepo\\MySolution\\~\\Views\\Articulo'."
Source: "System.IO.FileSystem"
StackTrace: " at System.IO.Enumeration.FileSystemEnumerator`1.CreateDirectoryHandle(String path, Boolean ignoreNotFound)\r\n at System.IO.Enumeration.FileSystemEnumerator`1..ctor(String directory, EnumerationOptions options)\r\n at System.IO.Enumeration.FileSystemEnumerable`1..ctor(String directory, FindTransform transform, EnumerationOptions options)\r\n at System.IO.Enumeration.FileSystemEnumerableFactory.UserFiles(String directory, String expression, EnumerationOptions options)\r\n at System.IO.Directory.InternalEnumeratePaths(String path, String searchPattern, SearchTarget searchTarget, EnumerationOptions options)\r\n at System.IO.Directory.EnumerateFiles(String path)"
TargetSite: {IntPtr CreateDirectoryHandle(System.String, Boolean)}
答案 0 :(得分:0)
EnumerateFiles("~/Views/Articulo")
不会扩展~
。您需要手动获取真实路径:
@using System.IO
@inject Microsoft.AspNetCore.Hosting.IHostingEnvironment env
<ul>
@{
var dir = System.IO.Path.Combine(env.ContentRootPath,"Views/Articulo");
}
@if(System.IO.Directory.Exists(dir))
{
@foreach (string articulo in Directory.EnumerateFiles(dir))
{
<li>
<a asp-controller="Articulo" asp-action="@articulo">@articulo</a>
</li>
}
}else{
<span>"No Files"</span>
}
</ul>