首页 > 解决方案 > C#如何从文件夹中选择文件

问题描述

我想从我的 C# 命令行项目的文件夹中选择一个文件。
例如,在 C:\deployment\Test_Folder 中有超过 10 个。我用这段代码显示了该文件夹的内容。

显示文件夹内容

例如,我想从该文件夹中选择第五个文件。我怎样才能做到这一点?

标签: c#

解决方案


这个怎么样。

使用 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];
        }

推荐阅读