简体   繁体   中英

C# file output prints more than 1 time

I have this code: Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CTesteM7
{
    internal class Borboletas
    {
        public string nomeAmigo { set; get; }
        public string nomeEspecie { set; get; }
        public int envergadura { set; get; }
        public int b { set; get; }
        public string classificacao { set; get; }
        public int quantidade { set; get; }
        public string pathInput { set; get; }
        public string pathOutput { set; get; }
    }
}

Main:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace CTesteM7
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Lista / Classe
            List<Borboletas> borboletas = new List<Borboletas>();
            Borboletas dados = new Borboletas();

            //Pedir ao utilizador o ficheiro de input
            Console.Write("Nome do ficheiro de input: ");
            dados.pathInput = Console.ReadLine();

            //Verificar se o ficheiro existe
            if (File.Exists(dados.pathInput))
            {
                //Ler o ficheiro
                StreamReader srf = new StreamReader(dados.pathInput);
                while (!srf.EndOfStream)
                {
                    // Buscar a linha do numero ou seja q n contem ;
                    var linha = srf.ReadLine();

                    if (!linha.Contains(';'))
                    {
                        dados.b = int.Parse(linha);
                    }
                    else
                    {
                        string[] strArray;
                        strArray = linha.Split(';');
                        dados.nomeEspecie = strArray[1];
                        dados.envergadura = Convert.ToInt32(strArray[2]);
                        borboletas.Add(dados);

                        //Ficheiro de output
                        dados.pathOutput = @"Output.txt";
                        StreamWriter swo = new StreamWriter(dados.pathOutput, append: true);
                        swo.WriteLine(dados.b);
                        //Verificações da classificação das borboletas e escrever para o ficheiro

                        if (dados.envergadura >= 0 && dados.envergadura <= 50)
                        {
                            dados.classificacao = "Pequena";
                            swo.WriteLine(dados.nomeEspecie + ":" + dados.classificacao);
                        }
                        else if (dados.envergadura >= 51 && dados.envergadura < 70)
                        {
                            dados.classificacao = "Grande";
                            swo.WriteLine(dados.nomeEspecie + ":" + dados.classificacao);
                        }
                        else if (dados.envergadura >= 70)
                        {
                            dados.classificacao = "Gigante";
                            swo.Write(dados.nomeEspecie + ":" + dados.classificacao);
                        }
                        else
                        {

                            Console.WriteLine("Erro");
                        }
                        swo.Close();
                    }

                }


                //Confirmação
                Console.WriteLine("\nOperação realizada com sucesso");
                Console.ReadKey();

                //Fechar os ficheiros
                srf.Close();


                //Adicionar os dados na lista
                borboletas.Add(dados);
            }
            else
            {
                //Caso o ficheiro não exista mostrar erro 
                Console.WriteLine("O ficheiro pedido não existe, insira um nome válido\n");
            }


        }
    }
}

And I want to print data from a file to output file but the variable dados.b (its the number 3) prints 3 times to output file and everytime I run the programm it adds everytime new text but I dont want the text to repeat it self, output file image

Anyone knows whats the problem? Thanks

swo.WriteLine(dados.b);

Its on the while loop, so you will execute it 3 times, You can add a flag with a count to execute it only one time or get it out from the while loop!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM