【发布时间】:2018-06-27 20:48:58
【问题描述】:
我正在制作一个小型益智游戏,并尝试使用 StringReader 将一些信息从文本文件加载到字符串中。它将加载到数据网格视图。该文本文件名为 TextFile1.txt,位于名为 Puzzles 的文件夹中。文本文件设置为始终复制到输出目录。
项目构建但不会加载数据网格视图中的项目。文本文件内容如下
x|y|direction|number|word|clue
5|5|down|1|love|Let _____ Rule
4|5|across|2|closed|Not Open
5|8|across|3|eraser|At the other end of a pencil
10|8|down|2|red|Hunt for _____ October
10|10|across|4|dallas|Redskin rival's city
9|5|down|3|dare|Triple Dog
13|8|down|4|relapse|To succumb again
11|12|across|5|cap|A night ____
代码
Clues clue_window = new Clues();
List<id_cells> idc = new List<id_cells>();
public String puzzle_file = Application.StartupPath + "\\Puzzles\\TextFile1.txt";
public Form1()
{
buildWordList();
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void buildWordList()
{
String line = "";
using (StringReader s = new StringReader(puzzle_file))
{
s.ReadToEnd();
line = s.ReadLine();//ignores the first line
while((line = s.ReadLine()) != null)
{
String[] l = line.Split('|');
idc.Add(new id_cells(Int32.Parse(l[0]), Int32.Parse(l[1]), l[2], l[3], l[4], l[5]));
clue_window.clue_table.Rows.Add(new String[] { l[3], l[2], l[5] });
}
}
}
【问题讨论】:
-
没问题?没问题?惊人的!开个玩笑,使用 StreamReader,而不是 StringReader。 StreamReader 从文件(或流)中读取文本,StringReader——顾名思义——从给定的字符串中读取文本/字符。如果您仍然感到困惑,请花一些时间阅读 StreamReader 和 StringReader 的文档。
-
另外,想想当您执行
s.ReadToEnd();后跟line = s.ReadLine();时会发生什么。在这种情况下,变量line将包含什么(为什么会这样)? -
如果它是一个小文件,我建议只使用
File.ReadLines()。使用更简单,并将字符串公开为Enumerable<string>
标签: c# datagridview stringreader