首页 > 解决方案 > 在 C# 中尝试读取文本文件并将其显示到控制台时遇到问题

问题描述

我正在尝试使用控制台应用程序在 c# 中制作一个琐事游戏。而且我无法让控制台读取文件。目前它所做的是说无法读取文件并且索引超出了数组的范围。但是随后会显示文本文件中的所有内容。我不确定我得到的文件无法读取,但随后文件被显示。

该文件是一个 .txt 文件,如下所示

What is another name for SuperMan?,the man of steel
What is Superman's only weakness?,kryptonite
What is the name of Batman's secret identity?,bruce wayne
Batman protects what city?,gotham city
How did Spiderman get his superpowers?,bitten by a radioactive sipder
This superheros tools include a bullet-proof braclets and a magic lasso.Who is she?,wonder woman
Which superhero has an indestructible sheild?,captain america
Which superhero cannot transformback into human form?,the thing
What villan got his distinctive appearance form toxic chemicals?,joker
What is the name of the archnemesis of the Fantastic Four?, dr doom

这是我用于读取和显示文件的代码。

static void Main(string[] args)
    {
        string filename = @"C:\Trivia\questions.txt";
        List<string> questions = new List<string>();
        List<string> answers = new List<string>();

        LoadData(filename, questions, answers);

        Console.WriteLine();
        questions.ForEach(Console.WriteLine);
        Console.WriteLine();
        answers.ForEach(Console.WriteLine);
    }

    static void LoadData(string filename, List<string> questions, List<string> answers)
    {
        try
        {
            using(StreamReader reader = new StreamReader(filename))
            {
                string line;

                while((line = reader.ReadLine()) != null)
                {
                    string[] lineArray = line.Split(',');
                    string annswer = lineArray[1];
                    string question = lineArray[0];
                    questions.Add(question);
                    answers.Add(annswer);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("File could not be read");
            Console.WriteLine(e.Message);
        }
    }

这是控制台上的输出。

File could not be read
Index was outside the bounds of the array.

What is another name for SuperMan?
What is Superman's only weakness?
What is the name of Batman's secret identity?
Batman protects what city?
How did Spiderman get his superpowers?
This superheros tools include a bullet-proof braclets and a magic lasso.Who is she?
Which superhero has an indestructible sheild?
Which superhero cannot transformback into human form?
What villan got his distinctive appearance form toxic chemicals?
What is the name of the archnemesis of the Fantastic Four?

the man of steel
kryptonite
bruce wayne
gotham city
bitten by a radioactive sipder
wonder woman
captain america
the thing
joker
dr doom

感谢您的建议。

标签: c#console-application

解决方案


通过使用您的代码,看起来您的 questions.txt 文件末尾可能有一些换行符。摆脱这些将解决您最初的问题,但真正的问题是您没有检查每一行以查看它是否包含逗号,也没有丢弃空数据行。这是一种兼具两者的方法:

static void LoadData(string filename, List<string> questions, List<string> answers)
{
    try
    {
        using (StreamReader reader = new StreamReader(filename))
        {
            string[] lines= 
                reader.ReadToEnd() //Read the whole file
                .Trim() //Get rid of whitespace at the beginning and end of the file, no more random newlines at the end.
                .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries) //Separate each line AND remove any empty lines.
            ;
            foreach (string _line in lines)
            {
                string line = _line.Trim();
                if (!line.Contains(','))
                {
                    Console.Error.WriteLine("!!! Line did not contain comma for separation");
                    Console.Error.WriteLine("!!!!!! " + line);
                    continue; //Just go on to the next line.
                }
                string[] lineArray = line.Split(',');
                string answer = lineArray[1];
                string question = lineArray[0];
                questions.Add(question);
                answers.Add(answer);
            }
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("File could not be read");
        Console.WriteLine(e.Message);
    }
}

当然,如果您想单独读取每一行,只需检查每一行以确保它在修剪后有任何长度(如果没有,请跳过它)并且它包含一个逗号(记录错误)


推荐阅读