保存文件 - xmlSerializer

时间:2014-11-27 19:08:40

标签: c# xml serialization xml-serialization streamwriter

我正在创建一个使用此代码序列化文件的方法:

        public void Save(Object file, Type type, String path)
    {
        // Create a new Serializer
        XmlSerializer serializer = new XmlSerializer(typeof(type));

        // Create a new StreamWriter
        StreamWriter writer = new StreamWriter(@path);

        // Serialize the file
        serializer.Serialize(writer, file);

        // Close the writer
        writer.Close();
    }

但是当我尝试构建时Visual Studio告诉我: “错误1找不到类型或命名空间名称'type'(您是否缺少using指令或程序集引用?)c:\ users \ erik \ documents \ visual studio 2013 \ Projects \ FileSerializer \ FileSerializer \ Class1.cs 16 65 FileSerializer “

为什么会这样?

**编辑*

有效的新代码:

        public void Save(Object file, String path, Type type)
    {
        // Create a new Serializer
        XmlSerializer serializer = new XmlSerializer(type);

        // Create a new StreamWriter
        TextWriter writer = new StreamWriter(path);

        // Serialize the file
        serializer.Serialize(writer, file);

        // Close the writer
        writer.Close();
    }

    public object Read(String path, Type type)
    {
        // Create a new serializer
        XmlSerializer serializer = new XmlSerializer(type);

        // Create a StreamReader
        TextReader reader = new StreamReader(path);

        // Deserialize the file
        Object file;
        file = (Object)serializer.Deserialize(reader);

        // Close the reader
        reader.Close();

        // Return the object
        return file;
    }

通过致电阅读:

myClass newClass = (myClass)Read(file, type);

通过致电保存:

Save(object, path, type);

谢谢! 埃里克

3 个答案:

答案 0 :(得分:7)

您的错误在new XmlSerializer(typeof(type));。您不需要typeofnew XmlSerializer(type);就足够了。

由于序列化file对象(并且可以在函数中确定其类型),因此您不必传递其类型。所以你的代码可以重写为

public void Save<T>(T file, String path)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StreamWriter writer = new StreamWriter(path))
    {
        serializer.Serialize(writer, file);
    }
}

答案 1 :(得分:0)

var serializer = new System.Xml.Serialization.XmlSerializer(type);

而不是

XmlSerializer serializer = new XmlSerializer(typeof(type));

答案 2 :(得分:0)

XmlSerializer需要Type个参数。 type已经是Type类型,因此您无需在其上调用typeof()。只有在括号内放置类名或泛型参数时才需要typeof()