簡體   English   中英

C#文件序列化錯誤

[英]C# File serialization error

大家好

在一年不看書之后,我試圖教自己如何再次進行C#文件序列化。 我的代碼中似乎有一個錯誤,但似乎無法修復或解決問題。 它與反序列化對象並將其讀入數組有關。

這是我的代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Serializing_Files
{
    [Serializable]
    public class Dog
    {
        public string Name { get; set; }
        public string Breed { get; set; }
        public int Age { get; set; }
        public bool IsFemale { get; set; }

        public Dog(string Name, string Breed, int Age, bool IsFemale)
        {
            this.Name = Name;
            this.Breed = Breed;
            this.Age = Age;
            this.IsFemale = IsFemale;
        }

        public override string ToString()
        {
            string dogInfo;

            dogInfo = "Name: "+this.Name;
            return dogInfo;
        }
    }

    public static class DogsFile
    {
        public static BinaryFormatter BFormatter { get; set; }
        public static FileStream FStream { get; set; }
        public static void WriteDog(string FileName, Dog NewDog)
        {
            FStream = new FileStream(FileName, FileMode.Append, FileAccess.Write);
            BFormatter = new BinaryFormatter();
            BFormatter.Serialize(FStream, NewDog);
            Console.WriteLine("{0} has been written to the file.", NewDog.Name);
            FStream.Close();
        }

        public static Dog[] ReadDogs(string FileName)
        {
            FStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            BFormatter = new BinaryFormatter();

            Dog[] DogArray = new Dog[FStream.Length];
            int i = 0;

            while (FStream.Position < FStream.Length)
            {
                DogArray[i] = (Dog)BFormatter.Deserialize(FStream); //line where error occurs
                Console.WriteLine("The file contans the following Dogs:");
                Console.WriteLine(DogArray[i].ToString());

                i++;
            }
            FStream.Close();
            return DogArray;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string filename = @"C:\Dogfile.ser";
            Dog[] allDogs = new Dog[3];

            allDogs[0] = new Serializing_Files.Dog("Scruffy", "Maltese", 3, true);
            DogsFile.WriteDog(filename, allDogs[0]);

            allDogs[1] = new Serializing_Files.Dog("Butch", "Bulldog", 1, false);
            DogsFile.WriteDog(filename, allDogs[1]);

            allDogs[2] = new Serializing_Files.Dog("Balo", "Chow Chow", 1, false);
            DogsFile.WriteDog(filename, allDogs[2]);

            DogsFile.ReadDogs(filename);
            Console.ReadLine();
        }
    }
}

我在第60行收到以下運行時錯誤:

mscorlib.dll中發生了類型為'System.Runtime.Serialization.SerializationException'的未處理異常

附加信息:輸入流不是有效的二進制格式。 起始內容(以字節為單位)為:0B-5F-5F-42-61-63-6B-69-6E-67-46-69-65-6C-64-01-01 ...

我使用多個教程的組合編寫了此文件,因此我可能會誤解了一些東西。 有人可以幫我了解我在做什么錯嗎? 我將非常感謝您可能提供的任何建議。

后續問題:添加到文件時,我正在使用“ FileMode.Append”。 我如何確保文件首先存在? 我應該一開始使用“ FileMode.Create”單獨運行一行代碼,還是可以使用更好的實踐方法?

提前謝謝了!

您的代碼不會崩潰。 可能是您創建了具有不同對象的文件(也許之后添加了一些屬性),現在它無法反序列化。 刪除文件,然后再次啟動程序。 文件模式工作正常。 無需更改。

另一點是序列化集合,而不是一個一個地寫對象。

public static class DogsFile
{
    public static BinaryFormatter BFormatter { get; set; }
    public static FileStream FStream { get; set; }
    public static void WriteDog(string FileName, Dog[] NewDog)
    {
        FStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
        BFormatter = new BinaryFormatter();
        BFormatter.Serialize(FStream, NewDog);
        FStream.Close();
    }

    public static Dog[] ReadDogs(string FileName)
    {
        FStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
        BFormatter = new BinaryFormatter();
        var DogArray = (Dog[])BFormatter.Deserialize(FStream);
        FStream.Close();
        return DogArray;
    }
}

在@Access Denied和@ZRT提出了一些有用的建議之后,這里是工作代碼。 多謝你們!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace Serializing_Files
{
    [Serializable]
    public class Dog
    {
        public string Name { get; set; }
        public string Breed { get; set; }
        public int Age { get; set; }
        public bool IsFemale { get; set; }

        public Dog(string Name, string Breed, int Age, bool IsFemale)
        {
            this.Name = Name;
            this.Breed = Breed;
            this.Age = Age;
            this.IsFemale = IsFemale;
        }

        public override string ToString()
        {
            string dogInfo;

            dogInfo = "Name: " + this.Name + Environment.NewLine + "Breed: " + this.Breed + Environment.NewLine + "Age: " + this.Age + Environment.NewLine;
            if (this.IsFemale)
            {
                dogInfo += "Gender: Female";
            }
            else
            {
                dogInfo += "Gender: Male";
            }
            dogInfo += Environment.NewLine;

            return dogInfo;
        }
    }

    public static class DogsFile
    {
        public static BinaryFormatter BFormatter { get; set; }
        public static FileStream FStream { get; set; }
        public static void WriteDog(string FileName, Dog[] NewDogs)
        {
            FStream = new FileStream(FileName, FileMode.Create, FileAccess.Write);
            BFormatter = new BinaryFormatter();
            BFormatter.Serialize(FStream, NewDogs);

            Console.WriteLine("The following dogs were written to the file:" + Environment.NewLine);

            for (int i = 0; i < NewDogs.Length; i++)
            {
                Console.WriteLine(NewDogs[i].ToString());
            }

            Console.WriteLine(Environment.NewLine);

            FStream.Close();
        }

        public static Dog[] ReadDogs(string FileName)
        {
            FStream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            BFormatter = new BinaryFormatter();
            var DogArray = (Dog[])BFormatter.Deserialize(FStream);

            Console.WriteLine("The file contains the following dogs:"+Environment.NewLine);

            for (int i = 0; i < DogArray.Length; i++)
            {
                Console.WriteLine(DogArray[i].ToString());
            }

            FStream.Close();
            return DogArray;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            string filename = @"C:\Dogfile1.ser";
            Dog[] allDogs = new Dog[3];

            allDogs[0] = new Dog("Scruffy", "Maltese", 3, true);

            allDogs[1] = new Dog("Butch", "Bulldog", 1, false);

            allDogs[2] = new Dog("Balo", "Chow Chow", 1, false);

            DogsFile.WriteDog(filename, allDogs);

            DogsFile.ReadDogs(filename);

            Console.ReadLine();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM