Excessive line breaking while creating file . txt C#?

Asked

Viewed 1,105 times

2

I’m trying to generate a file .txt from a code list recovered from the database. However, when the file is generated, line breaks come out in excessive number, as shown below:

Arquivo .txt gerado

The code is as below, being a foreach that traverses the entire list of objects recovered from the database and writes each code in the file . txt:

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

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


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

For line breaking, beyond the "\r\n", I have tried using line.Writeline(item) and line.**Write**(item + *Enviroment.NewLine*), and other variations. however, the problem persisted.

Does anyone know how I solve the same?

  • 4

    The problem seems to be in the content, must be full of items with nothing in codigos.

  • makes an if to check if the item is not empty before printing it

  • Or use the item.Trim() before he.

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

3

As stated by Maniero 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 it, I made a Join between the two tables and returned the search result. Thus, 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;
    }
  • 1

    It is a valid option, but depending on the number of records, it may not be the most performative. a Join can be a very heavy and less efficient operation if there are no appropriate index’s in case of high number of records.

Browser other questions tagged

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