Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# read txt file and store the data in formatted array

Tags:

c#

I have a text file which contains following

Name address phone        salary
Jack Boston  923-433-666  10000

all the fields are delimited by the spaces.

I am trying to write a C# program, this program should read a this text file and then store it in the formatted array.

My Array is as follows:

address
salary

When ever I am trying to look in google I get is how to read and write a text file in C#.

Thank you very much for your time.

like image 282
Csharp_learner Avatar asked Dec 27 '22 04:12

Csharp_learner


1 Answers

You can use File.ReadAllLines method to load the file into an array. You can then use a for loop to loop through the lines, and the string type's Split method to separate each line into another array, and store the values in your formatted array.

Something like:

    static void Main(string[] args)
    {
        var lines = File.ReadAllLines("filename.txt");

        for (int i = 0; i < lines.Length; i++)
        {
            var fields = lines[i].Split(' ');
        }
    }
like image 121
Welton v3.61 Avatar answered Feb 16 '23 18:02

Welton v3.61