Search code examples
c#filetextreadline

Whenever the text file changes a parameter in the text, create a new text file c#


I'm creating an application where every day I receive a text via URL and saved as a text file in the project folder, but every day the file is overwritten, I wanted to save a new file every day, Ex: 2845, 2846, 2847 and so on, only create a new one if the number variable is updated, using the "number" variable, I need to do a search and find the text file referring to the number with the details of the raffle, but I'm not getting it, could someone help me? I only get one file per day, I'm using this code to create the text

private void Details()
 {
     List<string> lastSorteio = new List<string>();
     string siteLotofacil = @"https://servicebus2.caixa.gov.br/portaldeloterias/api/lotofacil";

     var requisition = (HttpWebRequest)WebRequest.Create(siteLotofacil);
     requisition.MaximumAutomaticRedirections = 1;
     requisition.AllowAutoRedirect = true;
     request.CookieContainer = new CookieContainer();
     var response = (HttpWebResponse)requisicao.GetResponse();

     using (var responseStream = response.GetResponseStream())
     {
         using (var fileStream = new FileStream(Path.Combine(directory + "C:\\BoaSorte\\currentResult.txt"), FileMode.Create))
         {
             responseStream.CopyTo(fileStream);
         }
     }
 }

and I'm reading like this

   private void ReadFile()
 {
     var file = new StreamReader("C:\\BoaSorte\\currentresult.txt", Encoding.UTF8);
     stringline;

     while ((line = file.ReadLine()) != null)
         // Initialize array of 5 sequential integers.
         contestlist.Items.Add(line.ToString());

     file.Close();
 }

I have a Result class with the variables

public Resultado()
    {
        this.idLoteria = idLoteria;
        this.acumulado = acumulado;
        this.dataApuracao = dataApuracao;
        this.dataProximoConcurso = dataProximoConcurso;
        this.dezenasSorteadasOrdemSorteio = dezenasSorteadasOrdemSorteio;
        this.exibirDetalhamentoPorCidade = exibirDetalhamentoPorCidade;
        this.id = id;
        this.indicadorConcursoEspecial = indicadorConcursoEspecial;
        this.listaDezenas = listaDezenas;
        this.listaDezenasSegundoSorteio = listaDezenasSegundoSorteio;
        this.listaMunicipioUFGanhadores = listaMunicipioUFGanhadores;
        this.listaRateioPremio = listaRateioPremio;
        this.listaResultadoEquipeEsportiva = listaResultadoEquipeEsportiva;
        this.localSorteio = localSorteio;
        this.nomeMunicipioUFSorteio = nomeMunicipioUFSorteio;
        this.nomeTimeCoracaoMesSorte = nomeTimeCoracaoMesSorte;
        this.numero = numero;
        this.numeroConcursoAnterior = numeroConcursoAnterior;
        this.numeroConcursoFinal_0_5 = numeroConcursoFinal_0_5;
        this.numeroConcursoProximo = numeroConcursoProximo;
        this.numeroJogo = numeroJogo;
        this.observacao = observacao;
        this.premiacaoContingencia = premiacaoContingencia;
        this.tipoJogo = tipoJogo;
        this.tipoPublicacao = tipoPublicacao;
        this.ultimoConcurso = ultimoConcurso;
        this.valorArrecadado = valorArrecadado;
        this.valorAcumuladoConcurso_0_5 = valorAcumuladoConcurso_0_5;
        this.valorAcumuladoConcursoEspecial = valorAcumuladoConcursoEspecial;
        this.valorAcumuladoProximoConcurso = valorAcumuladoProximoConcurso;
        this.valorEstimadoProximoConcurso = valorEstimadoProximoConcurso;
        this.valorSaldoReservaGarantidora = valorSaldoReservaGarantidora;
        this.valorTotalPremioFaixaUm = valorTotalPremioFaixaUm;

    }

Solution

  • To have a single file per day in a given directory that can be overwritten or appended to, append the DateTime.Today date to the file name, Path.Combine the directory and file name to create the path, and Path.ChangeExtension to add the extension.

    private string GetFileName()
    {
        var dir = @"c:\BoaSorte";
        var datePart = DateTime.Today.ToString("MMddyyyy");
        var fileName = "Result";
        var file = Path
            .ChangeExtension(Path
            .Combine(dir, $"{fileName}{datePart}"), "txt");
    
        return file;
    }
    

    To create a unique file per call with a particular pattern, concatenate the file path in a loop and break it if the file doesn't exist by calling the File.Exists method.

    private string GetUniqueFile()
    {
        var dir = @"c:\BoaSorte";
        var suffix = DateTime.Today.ToString("MMddyyyy");
        var fileName = "Result";
        int fileNum = 1;
        string outFile;
    
        while (true)
        {
            outFile = Path.Combine(dir, $"{fileName}{suffix}{fileNum}.txt");
            if (!File.Exists(outFile)) break;
            fileNum++;
        }
    
        return outFile;
    }
    

    Better, have a utility method for this function that takes and concatenate the individual parts of the file. For example:

    internal static class Utils
    {
        internal static string GetUniqueFile(
            string dir,
            string fileName,
            string suffix,
            int seed,
            string extension)
        {
            string outFile;
    
            while (true)
            {
                outFile = Path
                    .ChangeExtension(Path
                    .Combine(dir, $"{fileName}{suffix}{seed}"), extension);
                if (!File.Exists(outFile)) break;
                seed++;
            }
    
            return outFile;
        }
    }
    

    Call it from your methods like this:

    private void Details()
    {
        var lastSorteio = new List<string>();
        var siteLotofacil = @"https...";
        var file = Utils.GetUniqueFile(
            @"c:\BoaSorte", "currentResult", "-", 2846, "txt");
    
        // ...
    
        using (var response = (HttpWebResponse)requisition.GetResponse())
        using (var responseStream = response.GetResponseStream())
        using (var fileStream = new FileStream(file, FileMode.Create))
        {
            responseStream.CopyTo(fileStream);
        }
    }