How to serialize a class to file in C#?

Asked

Viewed 285 times

3

How do I serialize a class to a C file#?

I have a class

[Serializable]
public class MyClass {
     public int MyNumber { get; set; }
     public string MyName { get; set; }


}
  • In what format? In what part do you have doubts - in the serialization, or in the recording for the disc?

  • Wanted a method to export to xml even

  • There are many pages in MSDN about serialization for XML. A simple google search returns an official documentation list. Why not start there?

  • I came to see with Stream, but I wanted a direct method, if it exists

  • After all, is the doubt in the serialization or in the recording? First you said you wanted to export to XML, now you’re talking about Streams that are used to write to disk. You have to be more specific.

  • I want to serialize to file, that is to write to disk. I am doing an integration and I will need to save the object on disk for another system to read it.

  • I was able to find this solution with stream. public Static void Writefile(Object obj, string filename) { byte[] data; using (Memorystream mStream = new Memorystream()) { Binaryformatter Formatter = new Binaryformatter(); Formatter.Serialize(mStream, obj); data = mStream.Getbuffer(); } File.Writeallbytes(filename, date); }

Show 2 more comments

3 answers

1

you can implement using Datacontract:

Your class with the attributes DataMember and DataContract

[DataContract]
public class MyClass 
{
    [DataMember]
    public int MyNumber { get; set; }

    [DataMember]
    public string MyName { get; set; }
}

extensive methods to convert from object to xml string and virse-versa.

public static class SerializeXMLUtils
{
    public static string serializeObjectToXmlString<T>(this T objectToSerialize)
    {
        var xmlString = string.Empty;
        using(var memoryStream = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memoryStream, objectToSerialize);
            memoryStream.Seek(0, SeekOrigin.Begin);

            using(var streamReader = new StreamReader(memoryStream))
            {
                xmlString = streamReader.ReadToEnd();
                streamReader.Close();
            }
            memoryStream.Close();
        }
        return xmlString;
    }

    public static T deserializeXmlStringToObject<T>(this string xmlString)
    {
        var deserializedObject = Activator.CreateInstance<T>();
        using(var memoryStream = new MemoryStream())
        {
            var xmlBinary = System.Text.Encoding.UTF8.GetBytes(xmlString);
            memoryStream.Write(xmlBinary, 0, xmlBinary.Length);
            memoryStream.Position = 0;

            var deserializer = new DataContractSerializer(typeof(T));
            deserializedObject = deserializer.ReadObject(memoryStream);
            memoryStream.close();
        }
        return deserializedObject;
    }

    public static void serializeObjectToFile<T>(this T objectToSerialize, string fileName)
    {
        using(var fileStream = new FileStream(fileName, FileMode.Create))
        {
            var serializer = new DataContractSerializer<T>();
            serializer.WriteObject(fileStream, objectToSerialize);
            fileStream.Close();
        }
    }

    public static T deserializeFileToObject<T>(this string fileName)
    {
        var deserializedObject = Activator.CreateInstance(typeof(T));
        using(var fileStream = new FileStream(fileName, FileMode.Open))
        {
            var deserializer = new DataContractSerializer(typeof(T));
            using (var xmlReader = XmlDictionaryReader.CreateTextReader(fileStream, new XmlDictionaryReaderQuotas()))
            {
                deserializedObject = deserializer.ReadObject(xmlReader, true);
                xmlReader.Close();
            }
            fileStream.Close();
        }
        return deserializedObject;
    }
}

once you have the extensive methods ready, just call them as follows:

//serializando
myObject.serializeObjectToFile<MyClass>(fileName);
//deserializando
var myObject = fileName.deserializeFileToObject<MyClass>();

if you need to serialize to a file, simply replace Memorystream with a Filestream.

Since you are using Datacontract, you can also serialize for JSON using Json.NET, as well as their classes will already be ready to exhibit through a webservice (preferably WCF).

1

You can implement a methods that receives a generic entity and performs Serialization.

        /// <summary>
        /// Serializes an object to an XML/Extensible Markup Language string.
        /// </summary>
        /// <typeparam name="T">The type of the object to serialize.</typeparam>
        /// <param name="value">The object to serialize.</param>
        /// <param name="serializedXml">Filled with a string that is the XmlSerialized object.</param>
        /// <param name="throwExceptions">If true, will throw exceptions. Otherwise, returns false on failures.</param>
        /// <returns>A boolean value indicating success.</returns>
        public static bool Serialize<T>(T value, ref string serializedXml, bool throwExceptions = false)
        {
        #if DEBUG
        #warning When in DEBUG Mode XML Serialization Exceptions will be      thrown regardless of throwExceptions paramter.
            throwExceptions = true;
        #endif

            if (value == null)
                if (throwExceptions)
                    throw new ArgumentNullException("The value is expected to be a non-null object.");
                else
                    return false;

            try
            {
                XmlSerializer xmlserializer = new XmlSerializer(typeof(T));

                using (StringWriter stringWriter = new StringWriter())
                using (XmlWriter writer = XmlWriter.Create(stringWriter))
                {
                    xmlserializer.Serialize(writer, value);

                    serializedXml = stringWriter.ToString();

                    return true;
                }
            }
            catch
            {
                if (throwExceptions)
                    throw;

                return false;
            }
        }

Follow link with the complete solution :

https://codereview.stackexchange.com/questions/100930/xml-serialization-helper-class

0

I will intonrei this solution

public static void WriteFile(object obj, string filename)
{
    byte[] data;
    using (MemoryStream mStream = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();

        formatter.Serialize(mStream, obj);
        data = mStream.GetBuffer();
     }

     File.WriteAllBytes(filename, data);
}
  • This serializes to a binary format, not to XML.

  • Didn’t really solve it. I’ll try with Xmlserializer I read on MSDN.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.