0

I am using C# and was wondering if there is a way to ask the user for a file name (in the console application) within the local documents. I don't really know how to structure this question when looking online but the code I have :

   static void Main(string[] args)
    {

        string[] random1 = System.IO.File.ReadAllLines(@"//..Random1.txt");

        foreach (string r1 in random1)
        {
            Console.WriteLine(r1);
        }

But ideally I would want something like:

static void Main(string[] args)
    {
        Console.WriteLine("Enter the name of the file you would like to see")
        // Following the input let's say " Potato.txt " is entered

        string[] chosenFile1 = System.IO.File.ReadAllLines(@"//..Potato.txt");

        foreach (string file in chosenFile1)
        {
            Console.WriteLine(file);
        }

I am not entirely sure how to go about it as usually its dependant on the path of the files , but I thought this way would be more appropriate as different users from different devices can try this out. Hope this makes sense , all help appreciated.

4

2 回答 2

0

我建议您不要向用户询问文件名,而是询问文件。文件名可能很长,通常,如果您作为程序员可以提供某种菜单,则用户不必输入它。

using System.IO;


    public static void Main(string[] args)
    {
        const string dir = @"e:\2";  // your folder here
        var files = Directory.GetFiles(dir);
        for (var i = 0; i < files.Length; i++)
        {
            Console.WriteLine($"{i}) {Path.GetFileName(files[i])}");
        }

        while (true)
        {
            Console.WriteLine("Enter the number of the file you would like to see or -1 to exit");
            var choice = Console.ReadLine();

            if (int.TryParse(choice, out var index) && index > -2 && index < files.Length)
            {
                if (index == -1)
                    return;

                string[] chosenFile1 = System.IO.File.ReadAllLines(files[index]);
                foreach (string file in chosenFile1)
                {
                    Console.WriteLine(file);
                }
            }
            else
                Console.WriteLine("Bad input. Repeat please.");
        }
    } 
于 2020-03-03T12:08:23.333 回答
-1

当您从终端执行此操作时,您可以将文件名传递给您的 .exe(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/main-and-command-args/command-line-参数)或使用 Console.ReadLine 读取程序中的输入(https://docs.microsoft.com/en-us/dotnet/api/system.console.readline?view=netframework-4.8

于 2020-03-03T11:37:36.823 回答