Save file - xmlSerializer

Erik picture Erik · Nov 27, 2014 · Viewed 21k times · Source

I'm creating a method to serialize a file using this code:

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();
}

But Visual Studio tells me this when I attempt to build: "Error 1 The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?) c:\users\erik\documents\visual studio 2013\Projects\FileSerializer\FileSerializer\Class1.cs 16 65 FileSerializer "

Why is this?

**EDIT*

New code that works:

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;
}

read by calling:

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

Save by calling:

Save(object, path, type);

Thanks! Erik

Answer

EZI picture EZI · Nov 27, 2014

Your error is in new XmlSerializer(typeof(type));. You don't need typeof. new XmlSerializer(type); is enough.

Since you serialize file object (and its type can be determined in the function) you don't have to pass its type. So your code can be re-written as

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

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