在Visual Studio中使用StringReader从文本文件读取

时间:2018-06-27 20:48:59

标签: c# datagridview stringreader

我正在制作一个小型益智游戏,并尝试使用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] });
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

首先,当您遇到此类问题时,请先检查Reader的路径( 我建议您使用StreamReader而不是StringReader。)

从我的角度来看,可能有两个问题:

1。读数可能由于找不到txt文件而无法工作。(进入该循环以进行检查时显示一个messageBox框)

2。s.ReadToEnd从流中读取所有内容。

该函数从文件中复制所有数据(从第一个字节到最后一个字节)。因此,下次您阅读一行时,它将返回null。

相关问题