Save int array to file

Dec 15 2008 9:10 PM
I am creating a version of Conway's Game of Life for a project and wish to save the state of the game grid. I have the game grid in an array [50,50] which represents whether a square is full or not.

I have the following code:
declare the grid array at the start of form class.
        private int[,] gridArrayMain = new int[50, 50];

then my method for saving the array:

private void saveButton_Click(object sender, EventArgs e)
        {
            saveArray.FileName = "grid.txt";
            dlgResult = saveArray.ShowDialog();

            if (dlgResult == DialogResult.Cancel)
                return;

            try
            {
                FileName = saveArray.FileName;
                streamwriter = new StreamWriter(FileName);

                for(int a = 0; a < gridArrayMain.Length; a++)
                    {
                        for(int b = 0; b < gridArrayMain.GetLength(a); b++)
                            {
                                streamwriter.Write(gridArrayMain[a, b]);
                            }
                    }
                streamwriter.Close();
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

With this code, the application compiles fine but when i click save and click save in the save dialog box i get the error "Index was outside the bounds of the array" Could anyone help me solve this problem? Thanks in advance!

Answers (1)