【问题标题】:read the second line from the text从文本中读取第二行
【发布时间】:2012-12-01 11:18:32
【问题描述】:

如何在visual studio 2012 c#中阅读第二行文字

         the txt file

         user123
         **12345**
         asdfd

我想在一个 button1_click 中获取第二行并将其显示给 textblock2

我确实尝试从这里学习 How do I read a specified line in a text file?

这里 How to skip first line and start reading file from second line in C#

但是这些都不起作用,因为我无法在我的代码中应用差异

有什么帮助吗?

================================================ ==================================== 很抱歉让大家感到困惑 实际上我真的缺乏编程经验,我几乎不知道如何使用它
现在我在windows8中使用vs2012,这是否意味着我在winrt中编码?

顺便说一句,我感谢您的所有帮助并成功地将答案应用于我的代码 这是实际代码

        var file = await ApplicationData.Current.LocalFolder.GetFileAsync(tb1.Text+".txt");
        var line = await FileIO.ReadLinesAsync(file);
        if (tb2.Text == line[2])
        {
            tb3.Text = (line[1]);
        }

【问题讨论】:

  • 你的代码有什么不同?
  • 你为什么要标记windows-8,是winrt吗?

标签: c# windows-8


【解决方案1】:
var desiredText = File.ReadLines("C:\myfile.txt").ElementAt(1);

File.ReadLines() 返回文件中行的 String[]。第二行的索引是1。见this。

【讨论】:

  • File.ReadAllLines 返回String[],而不是IEnumerable。索引不适用于IEnumerable
  • 哎呀,谢谢@Tilak。凌晨三点,还没醒。 :) 已修复。
  • 你的意思是它返回一个 IEnumerable 而不是 string[]
  • 代码正确。索引适用于数组。我的评论是为了你的解释。先喝啤酒:)
【解决方案2】:

试试

var desiredText = File.ReadLines("C:\myfile.txt");
textbox1.text = desiredText[1];

【讨论】:

    【解决方案3】:

    在开始捕获文件内容之前调用 .ReadLine()。

    从本质上讲,这将使读者跳过文件的第一行,而只阅读第二行及其后面的所有行。

    // Try this to take the second line.
    string line;
    using (var file_read = new StreamReader(your_file))
    {
        file_read.ReadLine(); 
        line = file_read.ReadLine();
    }
    textBox1.Text = line.ToString();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 2013-08-27
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 2019-05-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多