【问题标题】:C# file output prints more than 1 timeC# 文件输出打印超过 1 次
【发布时间】:2022-01-22 20:44:45
【问题描述】:

我有这个代码: 类:

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

主要:

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


        }
    }
}

我想将文件中的数据打印到输出文件,但变量 dados.b(它的数字 3)打印 3 次到输出文件,每次运行程序时它都会添加新文本,但我不想要文本自己重复一遍,output file image

谁知道问题出在哪里?谢谢

【问题讨论】:

  • 这不是Minimal 可重现的示例。尝试删除不相关的东西,您可能会自己发现问题
  • 那是因为在 StreamWriter swo = new StreamWriter(dados.pathOutput, append: true);您将 append 设置为 true,以便附加内容。如果您希望每次都创建一个新文件,则需要将 append 设置为 false。
  • 问题是,如果我删除 append: true ,它只会将输入文件的数字和最后一行打印到输出文件......
  • 然后在while循环前打开文件,循环后关闭。
  • 好吧,谢谢它总是添加更多文本的部分,但我仍然遇到数字 3 (dados.b) 重复自身(img I send)而不是只在顶部写 1 次的问题文件...

标签: c# file io


【解决方案1】:
swo.WriteLine(dados.b);

它在while循环中,所以你会执行3次,你可以添加一个带有计数的标志来只执行一次或者从while循环中取出!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 2014-07-19
    • 1970-01-01
    • 2011-02-16
    • 1970-01-01
    • 2021-06-27
    相关资源
    最近更新 更多