【问题标题】:Load and Save file using serialize in c#在 C# 中使用序列化加载和保存文件
【发布时间】:2017-04-28 05:47:44
【问题描述】:

我创建了一个代码,其中属性写为:

namespace ContactManagement
{
    public class Contact
    {
        public int Id{get; set;}
        public string Name { get; set; }
        public byte Age { get; set; }
        public DateTime Date { get; set; }
        public string City { get; set; }

        public Contact()
        {

        }
        public Contact(int id, string name, byte age, DateTime date, string city)
        {
            this.Id = id;
            this.Name = name;
            this.Age = age;
            this.Date = date;
            this.City = city;
        }
    }
}

写完之后,我写了一个文件处理的代码:

namespace ContactManagement
{
    public class ContactDB
    {
        string fileAddress = @"e://ContactDB.xml";

        static void Main(string[] args)
        {
            ContactDB dbObj = new ContactDB();
            List<Contact> lstContact = new List<Contact>(){
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
                new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            };
            dbObj.Save(lstContact);
            dbObj.Load();
            Console.ReadKey();
        }

        public void Save(List<Contact> lstContact)
        {
            FileStream wfs = new FileStream(fileAddress, FileMode.Create, FileAccess.Write);
            XmlSerializer serialobj = new XmlSerializer(typeof(ContactDB));
            serialobj.Serialize(wfs, lstContact);

            wfs.Close();
        }
        public List<Contact> Load()
        {
            List<Contact> listofContact = new List<Contact>();
            FileStream rfs = new FileStream(fileAddress, FileMode.Open, FileAccess.Read);
            XmlSerializer newserial = new XmlSerializer(typeof(ContactDB));
            string line;
            using (StreamReader sr = new StreamReader(fileAddress))
            {
                while ((line = sr.ReadLine())!= null)
                {
                    Console.WriteLine(line);
                }
            }
            return listofContact;
        }
    }
}

问题是编译后,我收到一个错误:生成 XML 文档时出错。

【问题讨论】:

  • 它说明错误是什么?
  • 这是错误:System.Xml.dll 中出现“System.InvalidOperationException”类型的未处理异常附加信息:生成 XML 文档时出错。
  • 是否有 InnerException?它应该为您提供更多信息。当它说“有错误”时,应该有关于错误是什么以及它发生在哪里的信息。您是否尝试过设置断点?或者将保存代码包装在 try/catch 中,throw ex; 并在其上放置一个断点。
  • 我做到了。我试着试着抓住,最后也一样。它产生的错误再次相同。它正在捕获列表的计数为 8。但它没有显示列表并且显示的错误是:生成 XML 文档时出错。

标签: c# serialization deserialization loading file-handling


【解决方案1】:

您正在为ContactDB 创建一个序列化程序,但正在传递一个List&lt;Contact&gt; 的实例。除非前者扩展后者,否则这是行不通的......

您需要为List&lt;Contact&gt; 创建一个序列化程序并继续将您的列表传递给序列化程序:

public void Save(List<Contact> lstContact)
{
    FileStream wfs = new FileStream(fileAddress, FileMode.Create, FileAccess.Write);
    XmlSerializer serialobj = new XmlSerializer(typeof(List<Contact>));
    serialobj.Serialize(wfs, lstContact);
    wfs.Close();
}

或者为您的列表添加一个属性到ContactDB 并将您的数据库传递给序列化程序。

public void Save(ContactDB db)
{
    FileStream wfs = new FileStream(fileAddress, FileMode.Create, FileAccess.Write);
    XmlSerializer serialobj = new XmlSerializer(typeof(ContactDB));
    serialobj.Serialize(wfs, db);

    wfs.Close();
}

这是一个适合我的解决方案:

        List<Contact> lstContact = new List<Contact>(){
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
            new Contact(){ Name="hello", Age=10, Date=new DateTime(2017,03,12), City="test"},
        };
        String xml;
        using (MemoryStream str = new MemoryStream())
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Contact>));
            ser.Serialize(str, lstContact);
            xml = Encoding.Default.GetString(str.ToArray());
        }
        List<Contact> lstContact2;
        using (MemoryStream str = new MemoryStream(Encoding.Default.GetBytes(xml)))
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Contact>));
            lstContact2 = (List<Contact>)ser.Deserialize(str);
        }

【讨论】:

  • 即使我为创建了属性的联系人创建了序列化程序,我也面临同样的错误:System.Xml.dll 中发生了“System.InvalidOperationException”类型的未处理异常附加信息:有生成 XML 文档时出错。
  • @ApoorvaSharma 我已经扩展了答案以提供您可以做什么的示例。
  • public void Save(List lstContact) { FileStream wfs = new FileStream(fileAddress, FileMode.Create, FileAccess.Write); XmlSerializer serialobj = new XmlSerializer(typeof(List));尝试 { serialobj.Serialize(wfs, lstContact); } 抓住 { 扔; } 最后 { wfs.Close();这就是我写的。但现在错误出现在 XML 文档中 (2, 2)
  • @ApoorvaSharma 这应该行得通。我添加了一个完整的解决方案。请与之比较。
  • @ApoorvaSharma 我从您的评论中复制了该方法,它对我有用。你到底是从哪里得到这个新错误的?
【解决方案2】:

retVal = (List)xml.Deserialize(ReadFs);

【讨论】:

  • 我试过你上面的代码。并在单独的函数中反序列化时向我显示错误。我们可以在不同的函数中进行序列化和反序列化吗? @kempeth
猜你喜欢
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2017-09-04
  • 2019-12-12
相关资源
最近更新 更多