serialize class item in textual documents

Asked

Viewed 172 times

3

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

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();
    }
}
  • you want to record each information separated by ; example 1;KEYLG1;Keyboard Logitech; 78.9 or some other format? I was in doubt about it.?

2 answers

4


You can generate an xml, binary or json file..

To save in text, xml mode..

Mark the class Product with the attribute Serializable

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

To Record:

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 the archive:

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

See the generated file:

inserir a descrição da imagem aqui

  • Opa milestones thank you very much, but this way I write my binary file would not? need to write text

  • Not this way you save in XML mode, if you open with notepad, Notepad++.. will be able to edit the contents.

  • I edited the answer by adding an image of the generated file.

  • It was worth more my dear, it solved my problem.

2

In json, using Newtonsoft.Json: http://www.newtonsoft.com/json/help/html/serializingjson.htm

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

Browser other questions tagged

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