I have a text file with the following numbers:

1 2 3
4 5 6

How do I read each individual number into an array?

It needs to move along each row so read in 1, 2 and then 3 into a array of 6 integers.
Then move to the second row and read 4 5 and 6...


Thank You

If your file is in the above mentioned format, then you can write the code something like this:

internal int[] loadArray(string path)
        {

            StreamReader sr = new StreamReader(path);
            int[] num=new int[0];

            try
            {
                while (!sr.EndOfStream)
                {
                    string[] temp = sr.ReadToEnd().Replace('\n',' ').Split(' ');
                    num = new int[temp.Length];

                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (!int.TryParse(temp[i], out num[i]))
                        {
                            throw new InvalidDataException();
                        }
                    }
                }

                return num;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sr.Close();
            }

        }

I did two examples for you, one is to use string array the other is to use char (which I prefer most in this case):

private void ReadingFile()
        {
            List<string> list = new List<string>();
            string path = @"C:\1\test11.txt";
            string[] lines = System.IO.File.ReadAllLines(path);

            //1. option:
            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split(' ');
                for (int j = 0; j < line.Length; j++)
                    list.Add(line[j]);
            }

            //2. option:
            List<string> list2 = new List<string>();
            for (int i = 0; i < lines.Length; i++)
            {
                char[] chars = lines[i].ToCharArray();
                for (int j = 0; j < chars.Length; j++)
                {
                    if (!Char.IsWhiteSpace(chars[j]))
                        list2.Add(chars[j].ToString());
                }
            }
        }

Hope it helps,
Mitja

This article has been dead for over six months. Start a new discussion instead.