Reading text file in C#

Asked

Viewed 58 times

1

I’m trying to make a small improvement in my automated algorithm on C#, my file ". txt" reads in the Email Inbox folder @empresa.com.br and writes only these @empresa.com.br in another file ". txt" in the Output folder disregarding the different ones, for example:
[email protected] [email protected] [email protected] [email protected] [email protected]

It turns out that only the [email protected] is being saved even putting the file.Writeline(item); The file is not playing one at the bottom of the other, breaking the line, follows my code:

class Program
{
    static void Main(string[] args)
    {
        string[] lines = File.ReadAllLines(@"C:\Entrada\emails.txt");

        int contador = 0;


        foreach (var item in lines)
        {
            if (item.Contains("@empresa.com.br"))
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Saida\Resultado.txt"))
                    {
                        if (item != "")
                            file.WriteLine(item);
                    }
            }
            contador++;
        }
        Console.WriteLine("Count: {0}", contador);
        Console.ReadLine();
    }
}

Could someone give me a hand at this point?

Hugs.

1 answer

2


This is happening because it is instantiating a new StreamWriter every time you spin a loop of your foreach. Just throw it out like this:

class Program
{
    static void Main(string[] args)
    {
        string[] lines = File.ReadAllLines(@"C:\Entrada\emails.txt");

        int contador = 0;


        using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\Saida\Resultado.txt"))
        {
            foreach (var item in lines)
            {
                if (item.Contains("@empresa.com.br"))
                {
                    if (item != "")
                        file.WriteLine(item);
                }
                contador++;
            }
        }
        Console.WriteLine("Count: {0}", contador);
        Console.ReadLine();
    }
}
  • 1

    Perfect Victor, had not paid attention to this issue of Streamwriter, now shows the 3 data saved in Output.

  • Good Leandro! D

  • 1

    :) I’ll share with colleagues for study, hugs.

Browser other questions tagged

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