C# 为什么反序列化没有';不行?

C# 为什么反序列化没有';不行?,c#,generics,serialization,C#,Generics,Serialization,我通常使用(反)序列化。我以前从未遇到过问题,但我认为这只是一个人类的错误,我看不出。。。 序列化可以完美地工作,但反序列化不能 这是我的代码: using System; using System.IO; using System.Windows.Forms; using Utils; using System.Xml; using System.Xml.Serialization; namespace Tests { public partial class MainForm :

我通常使用(反)序列化。我以前从未遇到过问题,但我认为这只是一个人类的错误,我看不出。。。 序列化可以完美地工作,但反序列化不能

这是我的代码:

using System;
using System.IO;
using System.Windows.Forms;
using Utils;

using System.Xml;
using System.Xml.Serialization;

namespace Tests
{
    public partial class MainForm : Form
    {
        private Test test;

        public MainForm()
        {
            InitializeComponent();
        }

        private void SaveButton_Click(object sender, EventArgs e)
        {
            try
            {
                test = new Test();
                test.MyInt = int.Parse(MyIntTextBox.Text);
                test.MyStr = MyStrTextBox.Text;
                test.Save();
                MessageBox.Show("Serialized!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadButton_Click(object sender, EventArgs e)
        {
            try
            {
                test = Test.Load();
                MyIntTextBox.Text = test.MyInt.ToString();
                MyStrTextBox.Text = test.MyStr;
                MessageBox.Show("Deserialized!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception caught", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

    }

    [Serializable]
    public class Test
    {
        public string MyStr { set; get; }
        public int MyInt { set; get; }

        public void Save()
        {
            using (StreamWriter sw = new StreamWriter("TestSerialized.xml"))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Test));
                xs.Serialize(sw, this);
                sw.Flush();
            }
        }

        static public Test Load()
        {
            Test obj = null;
            using (StreamReader sr = new StreamReader("TestSerialized.xml"))
            {
                XmlSerializer xs = new XmlSerializer(typeof(Test));
                if (!xs.CanDeserialize(XmlReader.Create(sr)))
                    throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", "TestSerialized.xml"));
                obj = (Test)xs.Deserialize(sr);
            }
            return (obj);
        }
    }
}
使用系统;
使用System.IO;
使用System.Windows.Forms;
使用UTIL;
使用System.Xml;
使用System.Xml.Serialization;
命名空间测试
{
公共部分类主窗体:窗体
{
私人测试;
公共表格(
{
初始化组件();
}
私有无效保存按钮\u单击(对象发送者,事件参数e)
{
尝试
{
测试=新测试();
test.MyInt=int.Parse(MyIntTextBox.Text);
test.MyStr=MyStrTextBox.Text;
test.Save();
显示(“序列化!”,“成功”,MessageBoxButtons.OK,MessageBoxIcon.Information);
}
捕获(例外情况除外)
{
MessageBox.Show(例如Message,“异常捕获”,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
私有无效加载按钮\u单击(对象发送者,事件参数e)
{
尝试
{
test=test.Load();
MyIntTextBox.Text=test.MyInt.ToString();
MyStrTextBox.Text=test.MyStr;
Show(“反序列化!”,“成功”,MessageBoxButtons.OK,MessageBoxIcon.Information);
}
捕获(例外情况除外)
{
MessageBox.Show(例如Message,“异常捕获”,MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
[可序列化]
公开课考试
{
公共字符串MyStr{set;get;}
公共int MyInt{set;get;}
公共作废保存()
{
使用(StreamWriter sw=newstreamwriter(“TestSerialized.xml”))
{
XmlSerializer xs=新的XmlSerializer(typeof(Test));
序列化(sw,this);
sw.Flush();
}
}
静态公共测试负载()
{
testobj=null;
使用(StreamReader sr=newstreamreader(“TestSerialized.xml”))
{
XmlSerializer xs=新的XmlSerializer(typeof(Test));
if(!xs.CanDeserialize(XmlReader.Create(sr)))
抛出新的NotSupportedException(string.Format(“无法加载文件。”,“TestSerialized.xml”);
obj=(测试)xs.反序列化(sr);
}
返回(obj);
}
}
}
它是一个基本表单,有两个文本框,一个用于测试类的每个属性,两个按钮,一个用于保存,另一个用于加载

别担心,我确保有一个文件要加载;)

我想创建一个通用(de)serliazer类,如:

public class Serializer<T>
{
    static public void Serialize(object obj, string path)
    {
        using (StreamWriter sw = new StreamWriter(path))
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            xs.Serialize(sw, obj);
            sw.Flush();
        }
    }

    static public T Dezerialize(string path)
    {
        T obj;
        using (StreamReader sr = new StreamReader(path))
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            if (!xs.CanDeserialize(XmlReader.Create(sr)))
                throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", path));
            obj = (T)xs.Deserialize(sr);
        }
        return (obj);
    }
}
公共类序列化程序
{
静态公共void序列化(对象对象对象,字符串路径)
{
使用(StreamWriter sw=新StreamWriter(路径))
{
XmlSerializer xs=新的XmlSerializer(typeof(T));
序列化(sw,obj);
sw.Flush();
}
}
静态公共T去序列化(字符串路径)
{
T-obj;
使用(StreamReader sr=新StreamReader(路径))
{
XmlSerializer xs=新的XmlSerializer(typeof(T));
if(!xs.CanDeserialize(XmlReader.Create(sr)))
抛出新的NotSupportedException(string.Format(“无法加载文件。”,path));
obj=(T)xs.反序列化(sr);
}
返回(obj);
}
}
但我有同样的问题:反序列化不起作用

编辑:我捕获到一个异常:“XML文档中存在错误(0,0)” 以及我要反序列化的XML文档(由XmlSerializer生成)


托托
45
谢谢你的帮助

遵循这个链接,它有确切的原因和解决方案


在您写入流之后,它被定位在您写入的XML之后的末尾。如果您尝试从同一个流中读取,则找不到根元素。因此您需要重新定位流(stream.Position=0)如果流支持该功能,或者您需要在写入流后关闭该流,然后打开一个新的流进行读取。”

您的代码无法工作,因为:

if (!xs.CanDeserialize(XmlReader.Create(sr)))
   throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", "TestSerialized.xml"));
if(!xs.CanDeserialize(XmlReader.Create(sr)))
抛出新的NotSupportedException(string.Format(“无法加载文件。”,“TestSerialized.xml”);
在这之后,从
sr
中再也没有什么可读的了,只有那时你才尝试反序列化——这就是它失败的原因。删除此代码。

删除这两行代码

if (!xs.CanDeserialize(XmlReader.Create(sr))
    throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", path));
if(!xs.CanDeserialize(XmlReader.Create(sr))
抛出新的NotSupportedException(string.Format(“无法加载文件。”,path));

或者在检查是否可以反序列化后重置流

您得到的错误是什么?我是法国人,因此捕获的本地化异常是:“Il existe une erreur dans le document XML(0,0)。”Translation:“XML文档中存在错误(0,0)”您能在这里显示您试图反序列化的实际XML吗?当然,但它是由Save方法生成的XML文档…toto 45错误肯定在XML的开头。您是否检查了XML开头的空白或任何附加字符?他正在以新流打开文件。通过defau,位置将为零lt.您的链接是关于使用相同的流来读写XML文件。我不使用相同的流。解决问题后,此链接的问题几乎相同;)天哪!这是一条测试这种方法的生产线。。。我忘记把它拿走了。。。问题解决了!
if (!xs.CanDeserialize(XmlReader.Create(sr))
    throw new NotSupportedException(string.Format("The file <{0}> cannot be loaded.", path));