Today we will write a program for creating a two dimensional Array from a input file.

Steps.

  1. Read input File.
  2. Calculate the row and column count.
  3. Read File line by line, split line by given delimiter and create two dimensional array.

C# Code

        public static int[,] Create2DMatrixFromFile(string inputFile
                                                   , char columnDelimiter)
        {

            if (File.Exists(@inputFile) == false)
            {
                throw new FileNotFoundException("Input file is not present ");
            }
            // Read All line from file

            string[] allLine = File.ReadAllLines(@inputFile);
            int rowCount = allLine.Count();

            int columnCount = allLine[0].Split(new char[] { columnDelimiter }, 
                                      StringSplitOptions.RemoveEmptyEntries).Count();

            int[,] matrix = new int[rowCount, columnCount];

            for (int rowCounter = 0; rowCounter < rowCount; rowCounter++)
            {
                string[] line = allLine[rowCounter].Split(columnDelimiter);
                for (int columnConter = 0; columnConter < columnCount; columnConter++)
                {
                    matrix[rowCounter, columnConter] = int.Parse(line[columnConter]);
                }

            }
           return matrix;

        }
 
input File

11,12,13,14,15
21,22,23,24,25
31,32,33,34,35
41,42,43,44,45
51,52,53,54,55
16,17,18,19,20
26,27,28,29,30
36,37,38,39,40
46,47,48,49,50