C # reads txt file and stores data in formatted array

I have a text file containing the following

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

      

all fields are delimited by spaces.

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

My array looks like this:

address
salary

      

When I try to look on google I get how to read and write a text file in C #.

Thanks a lot for your time.

+3


source to share


3 answers


You can use the File.ReadAllLines method to load a file into an array. Then you can use a for loop to loop through the strings and the Split method of the string type to split each string into a different array and store the values ​​in a 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(' ');
        }
    }

      

+6


source


Don't reinvent the wheel. You can use, for example, a fast csv reader where you can specify delimeter

which one you need.



There are many others on the internet, just search and select the one that suits your needs.

+2


source


This answer assumes you don't know how many spaces there are between each line on a given line.

// Method to split a line into a string array separated by whitespace
private string[] Splitter(string input)
{
    return Regex.Split(intput, @"\W+");
}


// Another code snippet to  read the file and break the lines into arrays 
// of strings and store the arrays in a list.
List<String[]> arrayList = new List<String[]>();

using (FileStream fStream = File.OpenRead(@"C:\SomeDirectory\SomeFile.txt"))
{
    using(TextReader reader = new StreamReader(fStream))
    {
        string line = "";
        while(!String.IsNullOrEmpty(line = reader.ReadLine()))
        {
            arrayList.Add(Splitter(line));
        }
    }
} 

      

+1


source







All Articles