【发布时间】:2019-12-03 23:38:31
【问题描述】:
我正在尝试用 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?
我真的不确定自己做错了什么。任何建议将不胜感激。
谢谢
【问题讨论】:
-
或者您可以使用单行:
Console.WriteLine(File.ReadAllText(filename));System.IO.File类有许多有用的静态方法,可用于将所有文件作为字符串(如上)或@ 987654326@,使用ReadAllLines,以及写入文件的方法。它是“reader”和“writer”类的一个方便的包装器。 -
如果您有新问题 - 提出新问题,不要将现有问题编辑为完全不同的问题。我回滚了您的更改,因为它在现有问题中提出了一个新问题,并且(更重要的是)使现有答案无效。 (问题本身实际上有规范的问答,显示了读取文本文件的各种方式......)