Streamwriter class

Asked

Viewed 117 times

4

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

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

Follow my code here:

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

        }

    }

2 answers

5


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

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

}

or

add Filemode.Append in the Filestream

using (var fileStream = new FileStream(@"C:\Temp\funcionarios.txt", FileMode.Append))
using (var streamWriter = new StreamWriter(fileStream))
{

}

Observing: 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 option

References

3

in his StreamWriter you can initialize with the parameter Append as true:

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

To the Encoding.Default it is necessary using System.Text;

  • Error pointing to true: "Cannot convert from "bool" to "System.Text.Encoding" and also "Encoding does not contain a setting to Default"

  • is just the variation of the overload, because you’re using a stream, and I’m using a string. Do as Virgilio showed

Browser other questions tagged

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