0

I currently have a text file which needs to be clean up and formatted properly. I am using c# read into the text file which currently reads all the contents from the file. However I only want to read certain content from that file.

for example file will contain a list of values shown below.

john,123,abc,ddd,eee,london 11,22,333,444,55,ss,dd,rr, qw,er,12.

I would like to only read values between abc and 444, the rest i do not want the program to read.

My programme so far

    var text = System.IO.File.ReadAllText(@"C:\Folder\filename.txt");
    Console.WriteLine("file contents = {0}", text);
    Console.ReadKey();

Would i need to loop through the entire file and display the values i want and is there a simple example

thanks

r1993
  • 183
  • 2
  • 2
  • 9

1 Answers1

1

You're working with CSV file. In case of simple CSV (it doesn't have commas and quotations in values) you can use Linq:

  var cleared = File
    .ReadLines(@"C:\Folder\filename.txt")
    .Select(line => line.Split(','))
    .Select(items => items.Skip(2).Take(8))
    .Select(items => items.Join(","));

  File.WriteAllLines(@"C:\MyData.csv", cleared); 

  // If you want to print out values to console instead of saving them to file: 
  // foreach(var line in cleared) 
  //   Console.WriteLine(line);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215