【问题标题】:Write and Read an Array to a Binary File将数组写入和读取到二进制文件
【发布时间】:2014-03-31 21:14:05
【问题描述】:

我有一个包含 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;
    }

【问题讨论】:

  • 您正在寻找序列化
  • 我已将我目前所拥有的内容添加到问题中
  • 您提供的代码有什么问题?
  • 我不知道,但我无法将数组写入文件
  • 你得到一个空文件吗?例外?

标签: c# arrays binaryfiles


【解决方案1】:

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

    [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 类的属性名称。)

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

【讨论】:

  • 在 sw = File.Open(@"C:\Players.bin", FileMode.Append); 处出现错误;
  • 错误信息是什么?也许您无权访问C: 根文件夹?您可以删除文件路径并使用 File.Open("Players.bin", ...),这是您的原始位置。
  • 我没有这个错误了,但我的方法出现了一个单独的错误:WriteToFile(playerArr, i);作为“我的名字在当前上下文中不存在”。这不允许程序运行,它与writeToFile方法中的int size有关
  • 我建议你把WriteToFile方法中的'size'参数去掉,这样你就会调用WriteToFile(playerArr),并在WriteToFile方法的开头添加以下行:int size = playerArr.Count();
  • 我在 bf.Serialize(sw, playerArr[x]); 处遇到错误- ArgumentNullException 未处理
猜你喜欢
  • 2014-09-25
  • 2022-01-28
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2021-08-29
  • 2014-01-07
  • 2015-06-16
相关资源
最近更新 更多