从二进制文件加载对象字典c#

时间:2016-12-02 01:29:39

标签: c# dictionary deserialization

我的程序将对象字典保存到二进制文件中,然后可以在以后加载该字典。

据我所知,我的保存功能正常。

public void GenerateFactionFile()
        {

            try
            {

                FileStream writerFileStream =
                    new FileStream(@"../../../Files/factions.bin", FileMode.Create, FileAccess.Write);

                this.formatter.Serialize(writerFileStream, this.ListOfFactions);


                writerFileStream.Close();
            }
            catch (Exception)
            {
                Console.WriteLine("Unable to save our friends' information");
            } 
        }

但我猜我的保存事情出了问题。

        public new void Load(string currentFile)
    {


        if (File.Exists(currentFile))
        {

            try
            {

                FileStream readerFileStream = new FileStream(currentFile,
                    FileMode.Open, FileAccess.Read);

                this.ListOfFactions = (Dictionary<int, FactionObject>)
                    this.formatter.Deserialize(readerFileStream);

                readerFileStream.Close();

            }
            catch (Exception)
            {
                Console.WriteLine("There seems to be a file that contains " +
                    "friends information but somehow there is a problem " +
                    "with reading it.");
            } 

        } 

    } 

因为当我尝试加载并将字典中的信息放入itemList时,我收到此错误,通知我字典中的第一项不存在...

  

mscorlib.dll中发生未处理的“System.Collections.Generic.KeyNotFoundException”类型异常

当我抛出该异常时,我在字典中的搜索显示它是空的。

为了信息,这就是默认的派系对象的样子

 [Serializable]
    public class FactionObject
    {

        public string factionName = string.Empty;
        public int espionage = 0;
        public int diplomacy = 0;
        public int mechanized = 0;
        public int armoured = 0;
        public int airAssault = 0;
        public int airCav = 0;
        public int airSuper = 0;
        public int airSupport = 0;
        public float overall = 0.0f;
        public CharacterObject[] characterArray = new CharacterObject[2];
        public int CharacterStartPoints;
    }

0 个答案:

没有答案