How to serialize a class to C # file?

3

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

I have a class

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


}
    
asked by anonymous 21.08.2015 / 22:10

3 answers

1

You can implement a method 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;
            }
        }

Link to the complete solution:

link

    
24.08.2015 / 13:46
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 object to an xml string and vice 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, just replace the MemoryStream with a FileStream.

Since you are using DataContract, you can also serialize to JSON using Json.NET , as well as your classes will already be ready to be exposed through a webservice (preferably WCF).

    
24.08.2015 / 14:14
0

I typed 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);
}
    
21.08.2015 / 22:41