c# - C#如何从文件夹中选择文件
问题描述
我想从我的 C# 命令行项目的文件夹中选择一个文件。
例如,在 C:\deployment\Test_Folder 中有超过 10 个。我用这段代码显示了该文件夹的内容。
例如,我想从该文件夹中选择第五个文件。我怎样才能做到这一点?
解决方案
这个怎么样。
使用 SelectFile(path) 调用,它将显示文件,以便用户可以使用向上和向下键进行选择
public static string SelectFile(string path)
{
bool FileSelect = false;
int FileChoice = 0;
List<string> Files = new List<string>();
foreach (string file in System.IO.Directory.GetFiles("."))
{
Files.Add(file);
}
if (Files.Count > 0)
{
FileSelect = true;
}
else
{
return "";
}
while (FileSelect)
{
Console.Clear();
Console.WriteLine("Select a file");
for (int i = 0; i < Files.Count; i++)
{
if (i == FileChoice)
{
Console.Write("[*]");
}
else
{
Console.Write("[ ]");
}
Console.WriteLine(Files[i]);
}
var key = Console.ReadKey();
if (key.Key == ConsoleKey.UpArrow)
{
FileChoice -= 1;
if (FileChoice == -1)
{
FileChoice = Files.Count - 1;
}
}
if (key.Key == ConsoleKey.DownArrow)
{
FileChoice += 1;
if (FileChoice == Files.Count)
{
FileChoice = 0;
}
}
if (key.Key == ConsoleKey.Enter)
{
FileSelect = false;
}
}
return Files[FileChoice];
}
推荐阅读
- python - 计算多个移动对象
- python - 为什么 python 中的字符串格式无法按预期工作?
- reactjs - ReactJS 轮询数据库或接收从服务器推送的数据
- javascript - 如何从 sfpg 中找到所有 img src 属性(单文件 PHP 库)
- java - JVMTI_ERROR_THREAD_NOT_ALIVE 错误使用多个活动和 OpenWeatherMap API
- python - 如何根据输入变量的长度更改函数
- c# - 是否可以在消息框中包含 if/else 语句的结果但多个值而不是一个
- javascript - Lodash groupby 字母表
- excel-formula - 在 Excel 中计算增长率
- css - Flexbox:当一组项目位于页面的最中心时,将单个项目放在底部