反序列化IPAddress时出现内存不足异常

时间:2013-04-19 16:58:37

标签: c# xml xml-serialization

当我尝试从MyConfig.xml反序列化时,我在

处遇到了内存不足的异常
System.Net.IPAddress.InternalParse(String ipString, Boolean tryParse)
System.Net.IPAddress.Parse(String ipString)
MyNamespace.IPRange.ReadXml(XmlReader reader)

IPRange.cs

public class IPRange : IXmlSerializable
{
    public IPRange () { }

    public IPAddress StartIP { get; set; }
    public IPAddress EndIP { get; set; }

    public XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(XmlReader reader)
    {
        this.StartIP = IPAddress.Parse(reader.GetAttribute("StartIP"));
        this.EndIP = IPAddress.Parse(reader.GetAttribute("EndIP"));
    }

    public void WriteXml(XmlWriter writer)
    {
        writer.WriteAttributeString("StartIP", this.StartIP.ToString());
        writer.WriteAttributeString("EndIP", this.EndIP.ToString());
    }
}

MyConfig.cs

public class MyConfig
{
    [XmlArrayItem("IPRange")]
    public List<IPRange> DMZ { get; set; }
}

MyConfig.xml

<?xml version="1.0" encoding="utf-8" ?>
<MyConfig>
    <DMZ>
        <IPRange StartIP="{some start ip}" EndIP="{some end ip}" />
        <IPRange StartIP="{some start ip}" EndIP="{some end ip}" />
    </DMZ>
</MyConfig>

我不知道我做错了什么。 请帮我解决这个问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

我已经通过在函数末尾写 reader.Read()来修复它...

public void ReadXml(XmlReader reader)
{
    this.StartIP = IPAddress.Parse(reader.GetAttribute("StartIP"));
    this.EndIP = IPAddress.Parse(reader.GetAttribute("EndIP"));

    reader.Read();
}