4

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.

3
  • Where are you confused? What have you tried? The hardest part would probably loading the file. Commented Mar 19, 2012 at 20:16
  • 4
    If you have control over it, I don't think spaces make for a great delimiter. You might want to change that. Commented Mar 19, 2012 at 20:16
  • I am able to read the file but not sure about loading...because for loading the file I want 2nd (address) and fourth field (salary). Commented Mar 19, 2012 at 20:18

3 Answers 3

6

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(' ');
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

3

Do not reinvent the wheel. Can use for example fast csv reader where you can specify a delimeter you need.

There are plenty others on internet like that, just search and pick that one which fits your needs.

Comments

1

This answer assumes you don't know how much whitespace is between each string in 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));
        }
    }
} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.