带有制表符自动完成的用户输入文件路径

User input file path with tab auto complete

我现在接受用户输入的文件路径:

Console.WriteLine("Input file path");
string path = Console.ReadLine();

try
{
    data = System.IO.File.ReadAllBytes(path);
}
catch
{
    Console.WriteLine("Invalid file path entered");
    System.Console.ReadKey();
    return 1;
}

但如果用户输入的路径不正确,他们将不得不重新输入整个内容。我意识到目前我的应用程序只会在用户输入错误时退出,我可以再次询问,但我仍然想让用户更容易一些。

相反,当用户在输入路径时使用 Tab 键时,我希望具有自动完成路径的 Windows 命令行功能。例如,如果我打开 cmd 并键入 cd C:\win 并按 TAB,cmd 将找到 C:\Windows.

是否可以将该功能添加到控制台应用程序以供用户输入?

你应该可以做到的。虽然它不是直接的并且可能没有现成的库,但你可以使用如下所示的东西:

 var userInputString = "";
    while (true){

    var char = Console.Read();
    // append to userInputString
    // search your directory and suggest the path using a combination of SetCursorPosition and Console.Write and bring the cursor back to user's current typing position. Hint: store Console.CursorLeft in another variable before you use SetCursorPosition so that you can set the cursor position back. 
    // If user presses <TAB> to accept the suggestion or of the file path that user keyed in exists "break" the loop.
    // So the loop never exits until the user either keys in correct path or accepts the suggestion
    }

一些可能对您有帮助的链接:

C# Console - set cursor position to the last visible line

https://msdn.microsoft.com/en-us/library/system.console.setcursorposition(v=vs.110).aspx

起初我认为清除特定的控制台行是不可行的,但快速搜索显示 nothing is impossible.

所以我创建了一个新的控制台应用程序,并开始思考如何让类似的东西发挥作用。下面是 "first working draft" - 我即将 [ 大量 ] 自己重构它,然后将生成的代码放在 Code Review 上,但这应该是足以让你入门。

程序使 Tab 键使用字符串数组作为数据自动完成当前输入,匹配它找到的第一个项目;如果你想要更智能的东西,你必须稍微调整一下(比如将当前文件夹的子路径作为数据,and/or 在每次连续按下 Tab 时迭代匹配项键):

class Program
{
    static void Main(string[] args)
    {
        var data = new[]
        {
            "Bar",
            "Barbec",
            "Barbecue",
            "Batman",
        };

        var builder = new StringBuilder();
        var input = Console.ReadKey(intercept:true);

        while (input.Key != ConsoleKey.Enter)
        {
            var currentInput = builder.ToString();
            if (input.Key == ConsoleKey.Tab)
            {
                var match = data.FirstOrDefault(item => item != currentInput && item.StartsWith(currentInput, true, CultureInfo.InvariantCulture));
                if (string.IsNullOrEmpty(match))
                {
                    input = Console.ReadKey(intercept: true);
                    continue;
                }

                ClearCurrentLine();
                builder.Clear();

                Console.Write(match);
                builder.Append(match);
            }
            else
            {
                if (input.Key == ConsoleKey.Backspace && currentInput.Length > 0)
                {
                    builder.Remove(builder.Length - 1, 1);
                    ClearCurrentLine();

                    currentInput = currentInput.Remove(currentInput.Length - 1);
                    Console.Write(currentInput);
                }
                else
                {
                    var key = input.KeyChar;
                    builder.Append(key);
                    Console.Write(key);
                }
            }

            input = Console.ReadKey(intercept:true);
        }
        Console.Write(input.KeyChar);
    }

    /// <remarks>
    /// 
    /// </remarks>>
    private static void ClearCurrentLine()
    {
        var currentLine = Console.CursorTop;
        Console.SetCursorPosition(0, Console.CursorTop);
        Console.Write(new string(' ', Console.WindowWidth));
        Console.SetCursorPosition(0, currentLine);
    }
}

感谢这个问题,很有趣!

我正在添加到 Mathieu Guindon 的优秀 以防其他人有这个用例。

如果你想要一个提示,邀请用户做出他们的选择,并希望能够保持提示,只是循环显示替换每个选项名称的选项,你所要做的就是更改ClearCurrentLine 方法,使其看起来像这样:

private static void ClearCurrentLine(int cursorLeft)
{
    var currentLine = Console.CursorTop;
    Console.SetCursorPosition(cursorLeft, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth - cursorLeft));
    Console.SetCursorPosition(cursorLeft, currentLine);
}

然后更改调用者以传递 cursorLeft 的适当值。愚蠢的例子:

var prompt = "Make your choice: ";
Console.Write(prompt);

// ...

ClearCurrentLine(prompt.Length)

这样'Make your choice: '不会被方法删除

您可以再次打印提示,但感觉更干净一些。