Ehsan Akbar
Ehsan Akbar

Reputation: 7299

read all lines in text file with separator

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

Upvotes: 3

Views: 13753

Answers (3)

Habib
Habib

Reputation: 223362

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();

Upvotes: 12

Matt Waldron
Matt Waldron

Reputation: 314

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.

Upvotes: 1

Justin Harvey
Justin Harvey

Reputation: 14682

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

Upvotes: 2

Related Questions