[英]How can I go to parent directories? (C#)
if (Console.ReadKey(true).Key == ConsoleKey.E)
{
Console.Clear();
Console.WriteLine("Enter path: ");
string Answer = Console.ReadLine();
foreach (var SelectedDir in System.IO.Directory.GetDirectories(Answer))
{
Console.WriteLine(SelectedDir + "\n");
}
string RootPath = Console.ReadLine();
Console.Clear();
Console.WriteLine("What would you like to do with " + RootPath + "?");
Console.WriteLine("A)Access Folder\nB)Delete Folder (Has to be empty)");
if (Console.ReadKey(true).Key == ConsoleKey.A)
{
AccessFolder(RootPath);
}
else if (Console.ReadKey(true).Key == ConsoleKey.B)
{
System.IO.Directory.Delete(RootPath);
}
AccessFolder(RootPath);
}
static void AccessFolder(string RootPath)
{
foreach (var SelectedRoot in System.IO.Directory.GetDirectories(RootPath))
{
Console.WriteLine(SelectedRoot + "\n");
}
string NextRoot = Console.ReadLine();
Console.Clear();
Console.WriteLine("What would you like to do with " + NextRoot + "?");
Console.WriteLine("A) Access Folder\nB)Delete Folder (Has to be empty)");
if (Console.ReadKey(true).Key == ConsoleKey.A)
{
AccessFolder(NextRoot);
}
else if (Console.ReadKey(true).Key == ConsoleKey.B)
{
System.IO.Directory.Delete(NextRoot);
}
}
我不知道如何 go 到父根。 我已經嘗試了 2 天,但無法提出任何建議。 我考慮過將目錄傳遞給一個字符串,每當用戶想要 go 到他所在目錄的父級時,路徑將等於 RootPath ,它將被傳遞到 AccessFolder 方法中。 我不確定這是否實用或是否會引起問題。 假設我有目錄“D:\StackOverflow\Test”,刪除最后一個 \ 之后的所有文本是否是個好主意,這樣目錄的路徑將是“D:\StackOverflow”? 任何幫助深表感謝。
以下將獲取父文件夾。
public static class DirectoryHelpers
{
/// <summary>
/// Traverse <seealso cref="folderName"/> backwards
/// </summary>
/// <param name="folderName">Existing folder</param>
/// <param name="level">Level backwards</param>
/// <returns>folder path <seealso cref="level"/> up</returns>
public static string UpperFolder(this string folderName, int level)
{
var folderList = new List<string>();
while (!string.IsNullOrWhiteSpace(folderName))
{
var parentFolder = Directory.GetParent(folderName);
if (parentFolder == null)
{
break;
}
folderName = Directory.GetParent(folderName)!.FullName;
folderList.Add(folderName);
}
return folderList.Count > 0 && level > 0
? level - 1 <= folderList.Count - 1 ? folderList[level - 1] : folderName
: folderName;
}
public static string ParentFolder(string sender) => sender.UpperFolder(1);
}
parentFolder
將為C:\OED\Dotnetland
硬編碼示例
string folderName = @"C:\OED\Dotnetland\VS2022";
string parentFolder = DirectoryHelpers.ParentFolder(folderName);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.