1

I have an array consisting of 1 string value and 2 int values, which I would like to write to a binary file.

It consists of name, index and score.

I have attached the array code below, how could I write this to a file?

Player[] playerArr = new Player[10];
        int index = 0;
        index = index + 1;                                  // when a new player is added the index is increased by one
        Player p = new Player(txtName3.Text, index, Convert.ToInt16(txtScore.Text));    // set the values of the object p
        p.refName = txtName3.Text;                          // set refName to be the string value that is entered in txtName
        p.refTotalScore = Convert.ToInt16(txtScore.Text);
        playerArr[index] = p;                               // set the p object to be equal to a position inside the array

I would also like to sort each instantiation of the array to be output in descending order of score. How could this be done?

The file handling code I have so far is:

    private static void WriteToFile(Player[] playerArr, int size)
    {
        Stream sw;
        BinaryFormatter bf = new BinaryFormatter();

        try
        {
            sw = File.Open("Players.bin", FileMode.Create);
            bf.Serialize(sw, playerArr[0]);
            sw.Close();
            sw = File.Open("Players.bin", FileMode.Append);
            for (int x = 1; x < size; x++)
            {
                bf.Serialize(sw, playerArr[x]);
            }
            sw.Close();
        }
        catch (IOException e)
        {
            MessageBox.Show("" + e.Message);
        }
    }

    private int ReadFromFile(Player[] playerArr)
    {
        int size = 0;
        Stream sr;
        try
        {
            sr = File.OpenRead("Players.bin");
            BinaryFormatter bf = new BinaryFormatter();
            try
            {
                while (sr.Position < sr.Length)
                {
                    playerArr[size] = (Player)bf.Deserialize(sr);
                    size++;
                }
                sr.Close();
            }
            catch (SerializationException e)
            {
                sr.Close();
                return size;
            }
            return size;
        }
        catch (IOException e)
        {
            MessageBox.Show("\n\n\tFile not found" + e.Message);
        }
        finally
        {
            lstLeaderboard2.Items.Add("");
        }
        return size;
    }
8
  • 5
    You are looking for serialization Commented Mar 31, 2014 at 21:17
  • I have added what I have so far to Question Commented Mar 31, 2014 at 21:19
  • And what's wrong with the code you provide? Commented Mar 31, 2014 at 21:24
  • I dont know but I cant write the array to the file Commented Mar 31, 2014 at 21:29
  • Do you get an empty file? An exception? Commented Mar 31, 2014 at 21:32

1 Answer 1

1

For the first part, you need to mark your class as Serializable, like this:

    [Serializable]
    public class Player

It's fine to Append to a new file, so you can change your code to this:

    sw = File.Open(@"C:\Players.bin", FileMode.Append);
    for (int x = 0; x < size; x++)
    {
        bf.Serialize(sw, playerArr[x]);
    }
    sw.Close(); 

(with the appropriate exception handling, and you'll obviously need to amend this if the file might already exist).

For the second part, you can sort an array like this using LINQ:

var sortedList = playerArr.OrderBy(p => p.Score);

If you require an array as output, do this:

var sortedArray = playerArr.OrderBy(p => p.Score).ToArray();

(Here, Score is the name of the property on the Player class by which you want to sort.)

If you'd like any more help, you'll need to be more specific about the problem!

Sign up to request clarification or add additional context in comments.

6 Comments

Im getting an error at sw = File.Open(@"C:\Players.bin", FileMode.Append);
What is the error message? Perhaps you don't have access to the C: root folder? You could remove the file path and just use File.Open("Players.bin", ...), which was your original location.
I dont have this error any more but i am getting a separate error on my method: WriteToFile(playerArr, i); as 'the name i doesnt exist in the current context'. This isnt allow the program to run, it is something to do with int size in the writeToFile method
I suggest you remove the 'size' parameter from the WriteToFile method, so you will call WriteToFile(playerArr), and add the following line at the start of the WriteToFile method: int size = playerArr.Count();
I am getting an error at bf.Serialize(sw, playerArr[x]); - ArgumentNullException was unhandled
|

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.