You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过索引动态选择任意数量的TXT文件并读取内容?

动态处理TXT文件选择的解决方案

你当前用switch写死case的方式确实没法适配数量不固定的文件,直接通过输入转换+范围校验就能实现动态处理,不需要重复编写case。

核心思路

  1. 将用户输入的字符转换为整数索引
  2. 校验索引是否在文件列表的有效范围内
  3. 若合法则直接调用ShowTxt展示对应文件内容,否则提示错误

修改后的代码

public void EditTxt()
{
    Console.Clear();

    string path = Environment.CurrentDirectory; // Path.Combine单参数无意义,直接使用当前目录即可
    var files = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly).ToList();

    // 优化:显示从1开始的索引,更符合用户输入习惯
    for (var index = 0; index < files.Count; index++)
    {
        var filename = Path.GetFileName(files[index]);
        Console.WriteLine($"[{index + 1}]  {filename}");
    }

    Console.Write("\n请输入文件对应的索引:");
    char choice = Console.ReadKey().KeyChar;
    Console.WriteLine("\n");

    // 替换switch的动态处理逻辑
    if (int.TryParse(choice.ToString(), out int inputIndex))
    {
        // 因为显示的索引从1开始,所以减1对应文件列表的0基索引
        int fileIndex = inputIndex - 1;
        if (fileIndex >= 0 && fileIndex < files.Count)
        {
            Console.WriteLine(ShowTxt(files[fileIndex]));
        }
        else
        {
            Console.WriteLine("输入的索引超出范围,请重新操作");
        }
    }
    else
    {
        Console.WriteLine("请输入有效的数字索引");
    }
}

public string ShowTxt(string file)
{
    return File.ReadAllText(file, Encoding.UTF8);
}

关键优化点

  • 把显示的索引改成从1开始,避免用户看到[0]却要输入1的困惑
  • 用int.TryParse做输入验证,防止用户输入非数字字符导致程序报错
  • 通过范围判断fileIndex >=0 && fileIndex < files.Count,自动适配任意数量的TXT文件,新增或删除文件都不用修改代码

内容的提问来源于stack exchange,提问作者Luminaire

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 13:24:25