这段代码实现从一个.txt文件读取数据,存放到一个二维数组里。


int[,] GetMatrixFromFile(string fileName)
        {
            int[,] matrix = null;
            StreamReader sr = new StreamReader(fileName);
            try
            {
                if (sr != null && sr.Peek() != -1)
                {
                    int Rand = Convert.ToInt32(sr.ReadLine());//秩
                    matrix = new int[Rand + 1, Rand + 1];//下标从1开始
                    for (int i = 1; i <= Rand; i++)
                    {
                        string temp = sr.ReadLine();
                        string[] temps = temp.Split(' ');
                        if (temps.Length == 2)
                        {
                            int line = Convert.ToInt32(temps[0]);
                            int rows = Convert.ToInt32(temps[1]);
                            temp = sr.ReadLine();
                            string[] strRows = temp.Split(' ');
                            if (rows == strRows.Length)
                            {
                                for (int j = 1; j <= rows; j++)
                                {
                                    int row = Convert.ToInt32(strRows[j - 1]);
                                    matrix[i, row] = 1;
                                }
                            }
                        }
                    }
                }
            }
            catch { }
            return matrix;
        }