serialize class item in textual documents

3

I would like to get the elements of my products class and save a txt file as my Serialization method would.

class Program
{
    static void Main(string[] args)
    {
        var products = new List<Product>
        {
            new Product(1, "KEYLG1", "Keyboard Logitech", 78.9),
            new Product(2, "MOULG1", "Mouse M280 Logitech", 55.5),
            new Product(3, "SMGM01", "Samgsung DUOS", 234.9),
            new Product(4, "NTASUS", "Notebooke Asus", 3500.99)
        };

        var fileName = @"c:\temp\Products.txt";    
        Serialize(fileName, products);      

    }

    /// <summary>
    /// Serializa os dados aqui.
    /// </summary>
    /// <param name="fileName"></param>
    /// <param name="products"></param>
    private static void Serialize(string fileName, List<Product> products)
    {


        throw new NotImplementedException();
    }
}
    
asked by anonymous 18.10.2016 / 19:52

2 answers

4

You can generate an xml, binary or json file.

To do save in text, xml mode ..

Mark the class Product with the Serializable attribute%

[Serializable]
public class Product
{
  //propriedades..
  //métodos...
  //..
}

To Write:

private static void Serialize(string fileName, List<Product> products){
    XmlSerializer serializer = new XmlSerializer(products.GetType());
    using (TextWriter writer = new StreamWriter(fileName))
    {
        serializer.Serialize(writer, products);
    }
}

To read from file:

public static List<Product> LerExemplo(String pathArquivo){
    if (!File.Exists(pathArquivo))
        throw new FileNotFoundException("Arquivo não encontrado " + pathArquivo);

    var serializer = new XmlSerializer(typeof(List<Product>));
    using (var reader = XmlReader.Create(pathArquivo))
    {
        var produtos = (List<Product>)serializer.Deserialize(reader);
        return produtos;
    }
}

View the generated file:

    
18.10.2016 / 20:54
2

In json, using Newtonsoft.Json: link

Product product = new Product();
product.ExpiryDate = new DateTime(2008, 12, 28);

JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;

using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
    serializer.Serialize(writer, product);
    // {"ExpiryDate":new Date(1230375600000),"Price":0}
}
    
18.10.2016 / 21:01