为什么C#,为什么在Visual Studio更新后使用TextReader抛出异常?Deserialize
在更新Visual Studio 2010后引发异常?
EDIT(问题变化):
我把它通过消除using
声明和TextReader gTr
手动调用Dispose
工作。
新问题:
为什么而与TextReader
(更新之后)阅读做了using
声明引起的错误?
我对此感到莫名其妙。我所做的只是更新Visual Studio,它不再有效。它在(几周)之前完全正常工作。它也匹配我读过的很多例子。我看不出有什么不对,或者如何缺少Root
,或者如何有error in XML document (0, 0)
。
//EXCEPTION
System.InvalidOperationException was caught
Message=There is an error in XML document (0, 0).
Source=System.Xml
InnerException: System.Xml.XmlException
Message=Root element is missing.
LineNumber=0
LinePosition=0
//SERIALIZE
SGlobalSettings gSettings = new SGlobalSettings();
XmlSerializer gXmls = new XmlSerializer(typeof(SGlobalSettings));
using (TextWriter gTw = new StreamWriter("global.xml"))
{
gXmls.Serialize(gTw, gSettings);
}
//DESERIALIZE
if (File.Exists("global.xml"))
{
SGlobalSettings global;
XmlSerializer gXmls = new XmlSerializer(typeof (SGlobalSettings));
using (TextReader gTr = new StreamReader("global.xml"))
{
global = (SGlobalSettings)gXmls.Deserialize(gTr);
}
}
//OBJECT
[XmlRootAttribute("Global")]
public class SGlobalSettings
{
public string key { get; set; }
public string last { get; set; }
public SGlobalSettings() { }
}
//XML
<?xml version="1.0" encoding="utf-8" ?>
<Global xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<key>KEY</key>
<last>LAST</last>
</Global>
感谢您的任何帮助!
好像使用您的代码,是反序列化对我很好。确保在<?xml version =“1.0”encoding =“utf-8”?>'之前没有任何空格。 – 2011-04-25 01:58:14
我只是执行上面的代码,序列化对象,然后反序列化,没有例外(VS2010)。也许别的东西导致它你没有包括在内? – StellarEleven 2011-04-25 02:00:59
@Bala:我得到它的工作和编辑我的问题,以反映我的新发现。在空格的注释中,我不创建xml文件,它使用'XmlSerializer'通过上面的代码完全生成。 – PiZzL3 2011-04-25 02:01:09