Search code examples
c#.netstreamwriter

Writing many variables into textfile


I've this piece of code:

using (StreamWriter writer = new StreamWriter("C:\\Users\\HP8200\\Desktop\\teste.txt"))
{            
    string numcont = _transaction.PartyFederalTaxID;

    double numenc = _transaction.BillToPartyID;
    double numfatura = _transaction.BillToPartyID;
    string zona = _transaction.BillToPartyCountryID;
    DateTime data = _transaction.CreateDate;
    string ean = _transaction.ATDocCodeId;
    double iva = _transaction.TotalTaxAmount;
    double precoantesdisc = _transaction.TotalLineItemDiscountAmount;
    double preconet = _transaction.TotalNetAmount;

    writer.WriteLine(numcont,";", numenc,";", numfatura,";", data,";", zona, Environment.NewLine , 
        ean,";", iva,";", precoantesdisc,";", preconet);
}

MessageBox.Show("gravou");

And it should save all those variables into the textfile I say but it only writes the first variable(numcont). What I need to do so it writes all the variables I need on that textfile? Feel free to ask for more code.


Solution

  • You need to format the string:

    writer.WriteLine(string.Format("{0};{1};{2};{3};{4}{5}{6};{7};{8};{9}",numcont, numenc, numfatura, data.ToString(), zona, Environment.NewLine, ean, iva, precoantesdisc, preconet));
    

    If you can use C# 6 syntax:

    writer.WriteLine($"{numcont};{numenc};{numfatura};{data.ToString()};{zona}{Environment.NewLine}{ean};{iva};{precoantesdisc};{preconet}");
    

    EDIT

    Use only day, month and year:

    writer.WriteLine($"{numcont};{numenc};{numfatura};{data.ToString("yyyyMMdd")};{zona}{Environment.NewLine}{ean};{iva};{precoantesdisc};{preconet}");
    

    The patter "yyyMMdd" can be arranged as you want. For example "dd.MM.yyyy"