我现在接受用户输入的文件路径:
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。
是否可以将此功能添加到控制台应用程序以供用户输入?
最佳答案
起初我认为清除特定的控制台行是不可行的,但快速搜索显示 nothing is impossible .
因此,我创建了一个新的控制台应用程序,并开始思考如何让类似的东西发挥作用。下面是“第一份工作草案”——我将要[大量]自己重构它,然后将生成的代码放在 Code Review 上。 ,但这应该足以让您入门。
程序使用字符串数组作为数据,使 Tab 键自动完成当前输入,匹配它找到的第一个项目;如果你想要更智能的东西(比如将当前文件夹的子路径作为数据,和/或在每次连续按下 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>
/// https://stackoverflow.com/a/8946847/1188513
/// </remarks>>
private static void ClearCurrentLine()
{
var currentLine = Console.CursorTop;
Console.SetCursorPosition(0, Console.CursorTop);
Console.Write(new string(' ', Console.WindowWidth));
Console.SetCursorPosition(0, currentLine);
}
}
感谢您提出这个问题,这很有趣!
关于c# - 带有制表符自动完成的用户输入文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39029847/