文本文件未在C#中显示到控制台

时间:2019-12-03 23:38:31

标签: c# console

我正在尝试用C#制作琐事游戏。我想为问题和答案加载一个简单的.txt文件。但是我似乎无法将问题显示在控制台上。这是在.txt文件中加载的代码

static void LoadData(string filename)
    {
        try
        {
            using(StringReader reader = new StringReader(filename))
            {
                string line;

                while((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch(Exception e)
        {
            Console.WriteLine("File could not be read");
            Console.WriteLine(e.Message);
        }
    }

这是我尝试向控制台显示问题的代码。现在发生的一切只是显示了文本文件的位置,而没有其他显示。

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

        LoadData(filename);
    }

文本文件如下

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?    

我真的不确定自己在做什么错。任何建议,将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:2)

您将要使用val m = """\(([^()]*)\)""".toRegex() val text = "aaaa (ferf ) veffef (frr) refef" val results = m.findAll(text).map{it.groupValues[1]}.toList() println(results) ,而不是StreamReader(通过StringReader或文件路径构造函数):

File.OpenRead

static void LoadData(string filename) { try { using (StreamReader reader = new StreamReader(filename)) { string line; while ((line = reader.ReadLine()) != null) { Console.WriteLine(line); } } } catch (Exception e) { Console.WriteLine("File could not be read"); Console.WriteLine(e.Message); } } 为您传递的字符串提供StringReader,在您输入的情况下,是文件名,而不是文件内容。

或者,如@Rufus L所指出的那样,您可以使用TextReader,它将为您提供所有在内存中的字符串数组,而不是像当前一样流式传输。

答案 1 :(得分:0)

尝试使用stringreader的StreamReader

using (StreamWriter text= new StreamWriter(@"file.txt"))
{
    text.WriteLine("The first line");
    text.WriteLine("This text is on the second line");
    text.WriteLine("And the third one.");
    text.Flush();
}
Console.WriteLine("The file has been successfully written.");

// appending a text to the file
using (StreamWriter sw = new StreamWriter(@"file.txt", true))
{
    sw.WriteLine("An appended line");
    sw.Flush();
}
Console.WriteLine("A new line has been successfully appended into the file.");

// printing the contents of the file
Console.WriteLine("Printing file contents:");

using (StreamReader sr = new StreamReader(@"file.txt"))
{
    string s;
    while ((s = sr.ReadLine()) != null)
    {
        Console.WriteLine(s);
    }
}
Console.ReadKey();