read all lines in text file with separator

10,766

Solution 1

Using LINQ you can do:

List<string[]> list = File.ReadLines("YourFile.txt")
                          .Select(r => r.TrimEnd('#'))
                          .Select(line => line.Split(','))
                          .ToList();
  • File.ReadLines would read the file line by line.
  • .Select(r => r.TrimEnd('#')) would remove the # from end of the line
  • .Select(line => line.Split(',')) would split the line on comma and return an array of string items.
  • ToList() would give you a List<string[]> back.

You can also use TrimEnd and Split in a single Select statement like below, (it would result in the same output):

List<string[]> list = File.ReadLines("YourFile.txt")
                          .Select(r => r.TrimEnd('#').Split(','))
                          .ToList();

Solution 2

Try this

string[] readText = File.ReadAllLines(path);

That will return an array of all the lines.

https://msdn.microsoft.com/en-us/library/s2tte0y1(v=vs.110).aspx

Solution 3

You can use a StreamReader to read all the lines in from a file and split them with a given delimiter (,).

var filename = @"C:\data.txt";
using (var sr = new StreamReader(filename))
{
    var contents = sr.ReadToEnd();
    var myarray = contents.
        Split(',');
}

Although I do prefer the LINQ approach answer further up.

Share:
10,766
Ehsan Akbar
Author by

Ehsan Akbar

Since January 2009, have 6 years plus of extensive hands on experience of website development. An experienced team lead and team player with excellent communication and interpersonal skills who has the ability to work independently under pressure Currently working as Senior Software Engineer/Team Lead at Ministry Of Interior. Masters in 2016 from the Azad University College of Information Technology, Qazvin, Iran. Leader and Co-Founder of software company SPAD System in 2013, Tehran, Iran

Updated on June 04, 2022

Comments

  • Ehsan Akbar
    Ehsan Akbar almost 2 years

    I have a file with this content :

    1,2,3,4,5#
    1,2,3,4,5#
    

    How can i read all lines using readline ?the important thing is i need to separate the values in each line ,i mean the first line's values 1,2,3,4,5 should be separated .

    Suppose i have an array named myarray that can save all values in first line :the array should be like this :

    myarray[0]=1
    myarray[1]=2
    myarray[2]=3
    myarray[3]=4
    myarray[4]=5
    

    I am so new in IO in c#

    Best regards