How to read 3 lines of a text file c#

Viewed 535

I designed a program that reads a specific line of the text file but I want to To read 3 lines and put them in the text box, for example, read lines 1, 3 and 5 only from the text file. Thank you

This is the code I want to modify to read more than one line, not a single line

  private void Button1_Click(object sender, EventArgs e)
    {
        openFileDialog1.ShowDialog();
        string text = System.IO.File.ReadAllText(openFileDialog1.FileName);
        string line = File.ReadLines(openFileDialog1.FileName).Skip(2).FirstOrDefault();
        TextBox1.Text = line;
    }
3 Answers

Try Where, i.e.

string[] lines = File
  .ReadLines(openFileDialog1.FileName)
  .Take(5) // optimization: we want 5 lines at most 
  .Where((line, index) => index == 0 || index == 2 || index == 4)
  .ToArray();

please, note that index is zero based (1st line has index == 0). In case of arbitrary indexes

HashSet<int> indexes = new HashSet<int>() {0, 2, 4};

string[] lines = File
  .ReadLines(openFileDialog1.FileName)
  .Take(indexes.Max() + 1) // optimization 
  .Where((line, index) => indexes.Contains(index))
  .ToArray();

System.IO.File.ReadLines() returns an IEnumerable.

On that, you can do things like use .ElementAt(index) to get specific lines, though keep in mind the first line is an index of 0. So you would actually want indices 0, 2, and 4 for for your example.

Where and Contains are your friends here :

Where has an overload that takes the index of array as 2nd argument.

var indicesToTake = new int[] { 1, 3, 5 };
string[] lines = File
  .ReadLines(openFileDialog1.FileName)
  .Where((x, i) => indicesToTake.Contains(i))
  .ToArray();

string fullText = string.Join(System.Environment.NewLine, lines); // and TextBox1.Text = fullText;
// or TextBox1.Lines = lines

you can also build the range of indices you want with linq, for instance if you want all odd indices between 1 and 100 :

var indicesToTake = Enumerable.Range(100).Where(i => i % 2 == 1);

As Dmitry Bychenko wrote, you can use other optimization tricks (Take to avoid checking all the array, especially if you want lines up to low index 10, but you much more lines after the last)

Related