Read file . txt, send Line and Delete it after confirmation of receipt

Asked

Viewed 802 times

2

This code is the fragment of a method that reads a text file and sends its content line by line, where each sent line receives a confirmation of receipt. I would like to delete from the file the sent line so get your confirmation of receipt, so that, if the transmission is interrupted in the middle of the file, I do not send the lines that have already been sent, thus avoiding duplicating the information received by the equipment. Someone could help me with this ?

 //Path ex : "/home/dhnqe/DataContainer.txt"
  if (File.Exists(path))
  {
    StreamReader file = new StreamReader(path);
    int numeroLinhas = File.ReadAllLines(path).Length;
    while ((linha = file.ReadLine()) != null)
    {
        linha = string.Format(linha + "\r\n");
        for (int i = 0; i< 3; i++)
        {
        controle = false;
        SendLineByRadio(address, line); //Enviar Linha
        int start = Environment.TickCount;
        do
        {
          ...
          ...
        } while (!controle && !timeout);

        if (controle)
        {
            if (Confirmation == "ReceiveOK")//Caso receba a confirmação
            {
                Console.WriteLine("Data Sent  = OK");
                clearData();
                controle = false;
                //INSERIR FUNCAO PARA APAGAR LINHA ENVIADA DO ARQUIVO TXT
                i = 10;
            }
        }
        if (timeout)
        {
            Console.WriteLine("Data Sent = Confirmation Timeout");//Caso não recebe a confirmacao
            clearData();
            controle = true;
            if (i == 2)
            {
                Console.WriteLine("Error: Response not received");
                clearData();
                Thread.CurrentThread.Abort();
            }

        }
     }
   }
  • Do you need to delete the lines? This is not very efficient. Is the confirmation synchronous? i.e. you only send a file line when you confirm the previous one? If so, why not just save the number of the last line sent in another temporary file ex:Datacontainer.txt.tmp ? In the end, you delete both. So you recover the state if you interrupt the execution of the application.

  • It is that when a line is sent the program waits for a message from the recipient confirming its receipt, home does not receive confirmation the transmission is aborted.

  • But, for example, if there was a file with 10 lines and the transmission was aborted in the fifth line the recipient had already received the previous four, and in that case if I send them again another transmission request, it would contain duplicate information, since the destination stores all transferred information.

  • As can also be seen in the code, this method is executed by a new Thread whenever there is a communication request, which is aborted if it does not receive confirmation of receipt of the line.

  • The idea of temporary file can work, I will try to implement here and test, I will return on this

  • Okay, changing a file you’re iterating on is not a very good idea. Don’t you have control over the server you send the information to? If a line was received and confirmation didn’t arrive, how do you know? in this case will forward the information, the ideal was to have a protocol to avoid these situations.

  • Yes there is a protocol where, I send the line and I wait for a Confirmation Message with a timeout, if you exceed this timeout the line is resubmitted, this happens 3 times, if you do not receive the reply the process is finished and the device needs to make another transmission request. This transmission is done by Radio Frequency, the destination is a microcontrolled equipment, so the only way to know if the received line is with the same message.

  • I also thought of reading the file and creating a list with the lines and while each line is sent I delete its entry, in case the transmission has to be aborted, I rewrite the file with the remaining lines

  • http://stackoverflow.com/questions/668907/how-to-delete-a-line-from-a-text-file-in-c

  • thanks guys, the temporary file worked, follow the answer to help someone in the future

Show 5 more comments

1 answer

1


Good guys the answer found was to create the variable lineCounter to count successfully sent lines

   //Path ex : "/home/dhnqe/DataContainer.txt"
    if (File.Exists(path))
    {
      int lineCount = 0; // VARIAVEL CRIADA PARA CONTAR AS LINHAS ENVIADAS
      StreamReader file = new StreamReader(path);
      int numeroLinhas = File.ReadAllLines(path).Length;
      while ((linha = file.ReadLine()) != null)
      {
          linha = string.Format(linha + "\r\n");
          for (int i = 0; i< 3; i++)
          {
          controle = false;
          SendLineByRadio(address, line); //Enviar Linha
          int start = Environment.TickCount;
          do
          {
            ...
            ...
          } while (!controle && !timeout);

          if (controle)
          {
              if (Confirmation == "ReceiveOK")//Caso receba a confirmação
              {
                  lineCount++; //INCREMENTAR, POIS A LINHA FOI ENVIADA E A RESPOSTA FOI RECEBIDA
                  Console.WriteLine("Data Sent  = OK");
                  clearData();
                  controle = false;
                 i = 10;
              }
          }
          if (timeout)
          {
              Console.WriteLine("Data Sent = Confirmation Timeout");//Caso não recebe a confirmacao
              clearData();
              controle = true;
              if (i == 2)
              {
                  Console.WriteLine("Error: Response not received");
                  clearData();
                  Thread.CurrentThread.Abort();
              }

          }
       }
     }

From the Variable to function ApagarLinhas() Read the file and copy the lines that were not created to a temporary file, then replace the file with the original, then erase the backup file.

  private void ApagarLinhas(string fileInput,int line_to_keep)
      {
        string line = null;
        int line_number = 0;
        string tempFile = fileInput + ".tmp";
        string backupFile = fileInput+"backup";
        using (StreamReader reader = new StreamReader(fileInput))
        {
            using (StreamWriter writer = new StreamWriter(tempFile))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    line_number++;

                    if (line_number <= line_to_keep)
                        continue;

                    writer.WriteLine(line);
                }
            }
        }
        File.Replace(tempFile, fileInput, backupFile);
        File.Delete(backupFile);                 

      }

Browser other questions tagged

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