【发布时间】: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