StreamWriter Class

4

My idea is to create a system to insert new employees through the CadastrarFuncionario() method, putting the properties of the class ( ID, nome, CPF ) inside a file named officials.txt.

With the logic used by me, the values are inserted successfully into the file. However, if I want to register a new employee after registering one, the data is overwritten and not added after jumping a line.

Here's my code:

    public static void CadastrarFuncionario()
    {          
        using (var fileStream = new FileStream(String.Format(@"C:\Files\funcionarios.txt"), FileMode.OpenOrCreate))
        using (var streamWriter = new StreamWriter(fileStream))
        {
            Funcionario f = new Funcionario();

            Console.WriteLine("ID: ");
            f.id = int.Parse(Console.ReadLine());

            Console.WriteLine("Nome: ");
            f.nome = Console.ReadLine();

            Console.WriteLine("CPF: ");
            f.cpf = int.Parse(Console.ReadLine());


            streamWriter.WriteLine("ID: " + f.id);
            streamWriter.WriteLine("Nome: " + f.nome);
            streamWriter.WriteLine("CPF: " + f.cpf);
            streamWriter.WriteLine("");

        }

    }
    
asked by anonymous 02.08.2017 / 15:40

2 answers

5

Use the second parameter setting to do this, and then remove FileStream , example:

using (var streamWriter = new StreamWriter(@"C:\Temp\funcionarios.txt", true))
{

}

or

add FileMode.Append in < FileStream

using (var fileStream = new FileStream(@"C:\Temp\funcionarios.txt", FileMode.Append)) using (var streamWriter = new StreamWriter(fileStream)) { } In the case of the question, use the second way, but remember that it is not necessary and your code can be summarized with the first one.

option

02.08.2017 / 15:56
3

In your StreamWriter you can initialize with the parameter Append to true:

 TextWriter tw = new StreamWriter("arquivo.txt", true, Encoding.Default);

For Encoding.Default is required using System.Text;

    
02.08.2017 / 15:55