어떻게 재귀 루프를 수행합니까? 먼저, 폴더 및 파일 목록을 루프 처리하고 싶습니다. 물론이 파일은 각각의 폴더 안에 있어야하며 HTML 및 CSS를 통해 웹에 목록을 표시 할 것입니다. 내 폴더와 파일을 저장하기 위해 List<DirectoryInfo>
과 List<FileInfo>
이 있습니다.반복적 인 파일/폴더 목록 루프 아웃
@foreach (DirectoryInfo folder in ViewBag.folders)
{
<p>@folder.Name</p>
foreach (FileInfo file in ViewBag.files)
{
if (folder.FullName == file.DirectoryName)
{
<p class="file" data-url="@file.FullName.Substring(file.DirectoryName.IndexOf("Content"))" style="margin-left:20px;">@file.Name</p>
}
}
}
을 그리고 이것은 각 폴더에있는 모든 폴더와 파일을 표시, 작동 :
이 같은 내보기에 기본 foreach 루프를 할 수 있습니다. 그러나 여기에 나오는 문제는 이미 추측 한 것처럼 하위 폴더입니다. 현재 모든 폴더는 하위 폴더를 포함하여 같은 목록에 있습니다. 그러나 이것은 분명히에만 하위 폴더의 첫 번째 계층을 위해 작동
내가이
<ol class="tree">
@{
int i = 1;
int subFolderi = 1;
foreach (DirectoryInfo folder in ViewBag.folders)
{
<li>
<label for="[email protected]">@folder.Name</label> <input type="checkbox" id="[email protected]" />
<ol>
@foreach (DirectoryInfo subFolder in ViewBag.folders)
{
if (folder.Name == subFolder.Parent.ToString())
{
<li>
<label for="[email protected]">@subFolder.Name</label> <input type="checkbox" id="[email protected]" />
<ol>
@foreach (FileInfo file in ViewBag.files)
{
if (subFolder.FullName == file.DirectoryName)
{
<li class="file" data-url="@file.FullName.Substring(file.DirectoryName.IndexOf("Content"))">@file.Name</li>
}
}
</ol>
</li>
}
subFolderi++;
}
@foreach (FileInfo file in ViewBag.files)
{
if (folder.FullName == file.DirectoryName)
{
<li class="file" data-url="@file.FullName.Substring(file.DirectoryName.IndexOf("Content"))">@file.Name</li>
}
}
</ol>
</li>
i++;
}
}
</ol>
처럼 뭔가를 할 수 그리고 그들의 상위 폴더 안에 하위 폴더를 놓을 게 아니라 하위 폴더 안에 하위 폴더. 또한이 하위 폴더는 상위 폴더 내에 한 번, 기본 폴더 목록에 한 번씩 두 번 표시됩니다.
질문은 그렇다면 하위 폴더에 서브 폴더와 파일을 계속 가져 오는 재귀 루프를 만들어야합니까? 아니면 LINQ를 사용하여 루프를 더 쉽게 만들기 위해 모든 것을 결합해야합니까? 또는 더 좋은 방법이 있습니까? 나는 여전히 HTML/CSS를 제어 할 수 있기 때문에 데이터 소스를 사용하고 모든 것을 자동으로 생성하는 jQuery 플러그인이나 ASP 컨트롤이없는 깨끗한 방법을 선호한다.
나는 폴더의 DisplayTemplate을 사용
<ol class="tree">
@printFolder(ViewBag.contentFolder)
</ol>
@helper printFolder(DirectoryInfo folder)
{
<li>
<label for="[email protected]">@folder.Name</label> <input type="checkbox" id="[email protected]" />
<ol>
@foreach(DirectoryInfo subFolder in folder.GetDirectories())
{
@printFolder(subFolder)
}
@foreach(FileInfo file in folder.GetFiles())
{
@printFile(file)
}
</ol>
</li>
}
@helper printFile(FileInfo file)
{
<li class="file" data-url="@file.FullName.Substring(file.DirectoryName.IndexOf("Content"))">@file.Name</li>
}
전체 파일/디렉토리 트리를 인쇄 하시겠습니까? – kaptan
@kaptan 내용 폴더 안의 전체 dir/file 트리입니다. 현재 폴더 및 파일 목록에 이미 모든 것을 포함하고 있지만 인쇄 방법이 확실하지 않습니다. – HenrikP