Excessive line break when creating C # .txt file?

2

I am trying to generate a .txt file from a code list retrieved from the database. However, when the file is generated, line breaks are excessive, as shown below:

  

Thecodeisasfollows,beingaforeachthattraversestheentirelistofobjectsretrievedfromthedatabaseandwriteseachcodeinthe.txtfile:

using(StreamWriterlinha=System.IO.File.CreateText(caminhoArquivo))foreach(varitemincodigos){linha.Write(item+"\r\n");
     }


return File(caminhoArquivo, "text/plain", nomeArquivo);

For line breakage, in addition to "\r\n" , I've already tried to use line. WriteLine (item) and line. **Write**(item + *Enviroment.NewLine*) , and other variations. however, the problem persisted.

Does anyone know how to solve it?

    
asked by anonymous 03.04.2017 / 15:53

2 answers

3

An if to validate the existence of content will suffice.

using (StreamWriter linha = System.IO.File.CreateText(caminhoArquivo))

    foreach(var item in codigos){
        if(!String.IsNullOrEmpty(item){
            linha.Write(item + "\r\n");
        }
    }

return File(caminhoArquivo, "text/plain", nomeArquivo);
    
03.04.2017 / 16:30
3

As said by the bigown in the comments, the problem was that null items were being returned in the bank search. At first, I was searching for the items and retrieving the codes with the following query:

        {
        var vendidos = (from c in _dbContext.VendaCoupon where c.DataVenda.Year == anoReferencia && c.DataVenda.Month == mesReferencia && c.Cancelado == false select c).ToList();

        List<string> codigos = new List<string>();

        foreach (var item in vendidos)
        {
            var getCodigo = (from c in _dbContext.Coupon where c.IdCoupon == item.IdCoupon && c.IdTipoCoupon == 4 select c.Codigo).FirstOrDefault();

            codigos.Add(getCodigo);
        }

        return codigos;
    }

To solve this, I made a join between the two tables and returned the search result. That way, the null items stopped being returned:

        {
        var vendidos = (from c in _dbContext.VendaCoupon join b in _dbContext.Coupon on c.IdCoupon equals b.IdCoupon where c.DataVenda.Year == anoReferencia && c.DataVenda.Month == mesReferencia && c.Cancelado == false && b.IdTipoCoupon == 4 select b.Codigo).ToList();

        return vendidos;
    }
    
03.04.2017 / 16:51