【问题标题】:Read from text file with StringReader in Visual Studio在 Visual Studio 中使用 StringReader 从文本文件中读取
【发布时间】: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&lt;string&gt;

标签: c# datagridview stringreader


【解决方案1】:

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

在我看来有两个问题:

1.读取可能无法正常工作,因为没有找到它的txt文件。(在进入该循环时显示一个消息框框以检查)

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

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

【讨论】:

    猜你喜欢
    • 2020-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多