-3

Consider below is text file:

Read:2019/09/24, 12345, abcdefg
Skip this line
Read:2019/09/24, 12345, abcdefg
Skip this line
Read:2019/09/24, 12345, abcdefg
Skip this line 
Read:2019/09/24, 12345, abcdefg
Skip 20 lines 

I am learning some tricky file reading in c#, I have problem in reading a text file. I understood how to read the file from bottom using Reverse function. But I need to read the file skipping bottom 20 lines and reading the alternative lines delimited by (,). Please help me to understand how to get this logic done.

Thank you

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • See [this answer](https://stackoverflow.com/a/452945/5062791), [Skip](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.skip?view=netframework-4.7.2) and [Take](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take?view=netframework-4.7.2) – ColinM Feb 28 '19 at 18:20
  • 1
    post your tries – Maciej S. Feb 28 '19 at 19:09

1 Answers1

0
public static void ReadFile()
    {
        List<string> lines = new List<string>();
        using (var sr = new System.IO.StreamReader(@"C:\test\tempfile.txt"))
        {
            string line = null;
            while((line = sr.ReadLine()) != null)
            {
                lines.Insert(0, line);
            }
            lines.RemoveRange(0, 20);
        }
        List<string> result = lines.Where((x, i) => i % 2 == 0).ToList();
      //Results:
      // Fourth-Read:2019/09/24, 12345, abcdefg
      // Third-Read:2019/09/24, 12345, abcdefg
      // Second-Read:2019/09/24, 12345, abcdefg
      // First-Read:2019/09/24, 12345, abcdefg
    }
tbl0892
  • 16
  • This wont necessarily read the file from the bottom up but it will give you the results you want. I assumed you had no data after the 20 lines you want to skip. – tbl0892 Feb 28 '19 at 19:49
  • Bottom 20 lines are garbage values with whitespace – Girish U R giri Mar 01 '19 at 03:08
  • Hi All thank you for your suggestions. I have read the file in reverse order using Reverse function. and stored all the values in list. My text file contains Ip Addr field in every line, so i have used linq query and fetched all the lines. – Girish U R giri Mar 04 '19 at 18:48
  • Please find the below code. List result =null; if(lines != null) { var list = lines.ToList(); result =list.Where(x => X.contains("IpAddr")) .ToList(); } if (result?.count >0) foreach( var item in result) { if(item.Contains(',')) foreach( var index in item.split(',").ToList()) { String Value = index.Trim(); // How to insert the list value to database; } } – Girish U R giri Mar 04 '19 at 18:54
  • Please help me in how to insert the values into database i have written code but its not working. – Girish U R giri Mar 04 '19 at 18:56