简体   繁体   中英

Read from text file with StringReader in Visual Studio

I am making a small puzzle game and am trying to load some info to a string from a text file using StringReader. It will load to a Data Grid View. The text file is called TextFile1.txt and is in a folder called Puzzles. The text file is set to always copy to the output directory.

The project builds but will not load the items in the data grid view. Text file reads as follows

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 ____

Code

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] });
            }
        }
    }

First of all when you have such a problem you first check the path of the Reader( I suggest you to use StreamReader instead of StringReader).

From my point of view there are 2 problems that can be:

1.The reading may not work because the txt file it's not found.(show an messageBox box when it's entering in that loop to check that)

or

2.That s.ReadToEnd reads everything from the stream.

That function copy all the data(from the first to the last byte) from the file. so the next time you Read a line it will return null.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM