将数组写入并读取到二进制文件

时间:2014-03-31 21:14:06

标签: c# arrays binaryfiles

我有一个由1个字符串值和2个int值组成的数组,我想写入二进制文件。

它由姓名,索引和分数组成。

我已经附上了下面的数组代码,我怎么能把它写到文件中?

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

我还想按照得分的降序对数组的每个实例化进行排序。怎么可以这样做?

我到目前为止的文件处理代码是:

    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;
    }

1 个答案:

答案 0 :(得分:1)

对于第一部分,您需要将您的类标记为Serializable,如下所示:

    [Serializable]
    public class Player

Append对新文件没问题,因此您可以将代码更改为:

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

(通过适当的异常处理,如果文件可能已存在,您显然需要修改此内容。)

对于第二部分,您可以使用LINQ:

对这样的数组进行排序
var sortedList = playerArr.OrderBy(p => p.Score);

如果需要数组作为输出,请执行以下操作:

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

(此处,Score是您要对其进行排序的Player类的属性名称。)

如果您需要更多帮助,您需要更具体地解决问题!