Resolved Edit and delete lines from a text file

titojd

Well-known member
Joined
Oct 12, 2018
Messages
63
Programming Experience
1-3
Hello Colleagues, I would like to take a doubt!
Personal apologies if this is something I could google, but as you know there are a lot of articles with no opinion on the subject, I spent days reading and got nowhere.
I prefer your opinion...

I recently changed my project, disconnected from the database and saved it in a Text file, as it was just a table and nothing confidential, I solved it this way, because I think that when installing it will make the process easier, but a doubt arose in me on how to edit, and delete just one line from the file following the Contest column which is the first column,

-Question: Is it possible to edit only a certain line in a text file with more than two thousand lines?
Is it possible to delete a particular row tabem?

if it is possible: what would be the best way (Indication),
If not, what would be the best way?
database or what other way?

I have a form like in the image where I can type the numbers and save
arraysarch.png


my Save button and your Save TXT method
C#:
private void salvarTXT()
        {
            if (!string.IsNullOrWhiteSpace(txtConcurso.Text))
            {
                resultUltimat();
                MessageBox.Show("Texto salvo com sucesso!");
            }
            else
            {
                MessageBox.Show("Insira um Resultado para salvar no arquivo Texto!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

 private void resultUltimat()// salva lista de numeros do sorteio (Resultado)  // save list of raffle numbers (Result)
        {
            // salva ultimo sorteio no arquivo texto na primeira linha e vai acrescentando linhas
            // saves the last draw in the text file on the first line and adds lines
            const string nomeArquivo = @"C:\BoaSorte\Banco\Resultados.txt";
            List<string> linhas = File.ReadLines(nomeArquivo).ToList(); // Passo 1

            if (linhas.IndexOf(txtConcurso.Text + "," + ResultTextBox[0].Text + "," + ResultTextBox[1].Text + "," + ResultTextBox[2].Text + "," + ResultTextBox[3].Text + "," + ResultTextBox[4].Text
               + "," + ResultTextBox[5].Text + "," + ResultTextBox[6].Text + "," + ResultTextBox[7].Text + "," + ResultTextBox[8].Text + "," + ResultTextBox[9].Text
               + "," + ResultTextBox[10].Text + "," + ResultTextBox[11].Text + "," + ResultTextBox[12].Text + "," + ResultTextBox[13].Text + "," + ResultTextBox[14].Text) >= 0);
            //Element found in list.
            //MessageBox.Show("Resultado já Exists no arquivo de texto!");
            else
            {
                linhas.Insert(0, txtConcurso.Text + "," + ResultTextBox[0].Text + "," + ResultTextBox[1].Text + "," + ResultTextBox[2].Text + "," + ResultTextBox[3].Text + "," + ResultTextBox[4].Text
             + "," + ResultTextBox[5].Text + "," + ResultTextBox[6].Text + "," + ResultTextBox[7].Text + "," + ResultTextBox[8].Text + "," + ResultTextBox[9].Text
             + "," + ResultTextBox[10].Text + "," + ResultTextBox[11].Text + "," + ResultTextBox[12].Text + "," + ResultTextBox[13].Text + "," + ResultTextBox[14].Text); // Passo 2
                File.WriteAllLines(nomeArquivo, linhas);
                //MessageBox.Show("Gravndo!");
            }
        }

my text file is being saved like this

arquivoTEXTO.png

How I tried the edit method

C#:
 private void editar()
        {
            try
            {
                using (StreamReader lendo = new StreamReader(@"C:\BoaSorte\Banco\Resultados.txt"))
                {
                    while (lendo.Peek() != -1)
                    {
                        int linha = File.ReadAllLines(@"C:\BoaSorte\Banco\Resultados.txt").GetLength(0);

                        for (int i = 1; i <= linha; i++)
                        {
                            if (lendo.ReadLine() == txtConcurso.Text)
                            {
                                string caminhoArquivo = @"C:\BoaSorte\Banco\Resultados.txt";

                                //Numero da linha que o conteúdo vai ser alterado
                                // Line number where the content will be changed

                                //Lendo arquivo e atribuindo em um array de string
                                //Reading file and assigning it to a string array

                                string[] arquivo = File.ReadAllLines(caminhoArquivo);

                                //Mudando o valor da linha informada
                                // Changing the value of the informed line

                               // arquivo = ResultTextBox[i].Text; //here is the error
                                lendo.Close();
                                //gravando o conteúdo por cima do arquivo,porem trava nessa linha falando que ja esta em uso
                                // recording the content over the file, but it hangs on this line saying that it is already in use
                                System.IO.File.WriteAllLines(caminhoArquivo, arquivo);
                            }
                        }
                    }
                }
            }

            catch (Exception)

            {

            }

I appreciate any advice, opinion or indication
 
hello @Skydiver, Thank you very much for the suggestion, I read the documentation and I liked it, I think it meets my needs, after all my database is just a table with 16 columns, I need to edit or delete it if there is a typing error at the time of insertion , I'll read more carefully, after all, I didn't know, but SqLite I never used either.
 
This means that you cannot "delete", "add" or even "change" a "Line" in a text file: to do this, you must create a new file, copy everything up to the point of change over, then write your new line in the output file (insert a line), skip a line in the input file (delete a line) or do both (change a line), copy the rest of the file and close both files, delete the original and rename the new one with the old filename.

This isn't accurate. As I mentioned earlier, it's possible, particularly in the case of a fixed width text file like we have here, to open the file, seek to the end, read 50 bytes (or however many comprise a line), seek to the middle, and write those 50 bytes in place, overwriting the data in the middle of the file, then shorten the file by 50 bytes. This effectively erases a middle record by replacing it with the one from the end.

This is very different and hugely faster than your approach of copying the entire file up to the mid point, omitting a line, then copying the rest of the file.

In either case you end up with a file that lacks the middle record, but my approach reads/writes less than 100 bytes, yours reads/writes nearly the entire file

The two files end up looking different (different order) but contain the same info. SQLServer definitely does not rewrite its entire data file when you delete a record located in the middle (but equally, it doesn't move data from the end; it's far more sophisticated than that).
 
Last edited:
just a doubt @cjard, using SqLite, when installing the application on another pc, will I have to install a database? Or is it built into the app?

The idea of an embedded DB like SQLite or LiteDB(thanks for the intro @Skydiver.. first i heard of it) is that there isnt a separate db software to install, there is just a DB file with pre-made data, if necessary, that is installed with the app.

To this end a SQLite DB is no different to a text file; it is deployed with your app, just like a text file, and your app manipulates it, just like a text file.. it's just that the driver for the DB is much more capable. By spending hours writing code that manipulates a text file, you are merely writing all the same kind of code that the DB driver already does (it can already delete record ID 123 on demand, in 1 line of code. For you to achieve the same in your text file approach will take multiple lines of code, and more effort)

We should always be careful not to confuse a situation we don't understand with a situation that is difficult. Me might understand text files and not databases, but it doesn't mean that text file is the easier approach
 
I let go of my hand. I'm zero on this subject, I'm wrapped up in so much information, I'm going to continue with the Sql server, I'm used to it, I'm already out of my head, let's forget about this subject, a hug to all. :)
 
We should always be careful not to confuse a situation we don't understand with a situation that is difficult. Me might understand text files and not databases, but it doesn't mean that text file is the easier approach

Just like digging a long deep trench... there's the option of using a shovel, or using an excavator.
 
para você @Skydiver e @Pablo, muito obrigado, você me ajudou com minhas dúvidas, mas meu problema hoje é o tempo, eu quase teria que elaborar o projeto quase do zero, LiteDB é "Fácil" mas tem que se acostumar, vou começar a usar nos próximos projetos para pegar o jeito, até fiz o Insert(), List(), mas na edição deu ruim, como eu tenho um ID definido (Concurso) Não consegui me encontrar, lerei mais sobre o LiteDB oportunamente, um abraço.
 
Last edited:
Back
Top Bottom