【问题标题】:How to access my .txt fine in C# Form, I need first line of .txt file to print out on TextBox [closed]如何在 C# 表单中访问我的 .txt 文件,我需要 .txt 文件的第一行才能在 TextBox 上打印出来 [关闭]
【发布时间】:2019-11-29 21:43:14
【问题描述】:
private void Button1_Click(object sender, EventArgs e)
{
    int counter = 0;
    string line;
    System.IO.StreamReader file = new System.IO.StreamReader("Sav1.txt");
    while ((line = file.ReadLine()) != null)
    {
        richTextBox1.Items.Add(line);
        counter++;
    }
}

如何在 C# 表单中正常访问我的 .txt,我需要 .txt 文件的第一行才能在 TextBox 上打印出来。这个不行。

【问题讨论】:

  • 欢迎来到 StackOverflow!您能否详细说明 not working 部分?这是非常模棱两可的。它不工作怎么办?你目前的结果是什么,你想要的结果是什么?您是否收到任何错误消息?注意:您的计数器目前除了递增之外没有做任何事情。你也可以改用while (!file.EndOfStream()) { }
  • 这是什么:richTextBox1.Items.Add(line);?您似乎正在尝试将项目添加到列表框。你可以写richTextBox1.Text = File.ReadLines("Sav1.txt").First();。如果Sav1.txt 位于当前工作目录中,则此设置。请改用完整路径。

标签: c# winforms textbox


【解决方案1】:

如果你只想要第一行:

int counter = 0;
string line;
using (System.IO.StreamReader file = new System.IO.StreamReader("Sav1.txt"))
{
    while ((line = file.ReadLine()) != null)
    {
        if (counter == 0)
        {
            richTextBox1.Items.Add(line);
        }
        counter++;
    }
}

如果您不需要该文件来做其他任何事情,您可以这样做:

    string line;
    using (System.IO.StreamReader file = new System.IO.StreamReader("Sav1.txt"))
    {
        if ((line = file.ReadLine()) != null)
        {
            richTextBox1.Items.Add(line);
        }
    }
}

请注意,无论哪种方式,您都应该始终使用StreamReader 实例的Dispose(最简单的方法是using 语句)。

【讨论】:

  • @Symon 点已被占用。答案已更新
【解决方案2】:
public string[] readText = File.ReadAllLines(here your file address + "\\filename.txt");
richTextBox1.Text = readText[0];

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关 why 和/或 如何 此代码回答问题的附加上下文可提高其长期价值.
  • 不,不,我将索引设置为 0,这意味着只会拾取第一行
猜你喜欢
  • 1970-01-01
  • 2016-05-13
  • 1970-01-01
  • 2013-10-09
  • 2016-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
相关资源
最近更新 更多