Home > Net >  How to overwrite a string in a text document
How to overwrite a string in a text document

Time:12-05

Doing a ATM Machine for my computer science project and I wanted to know how to overwrite a specific string of text in a text document. Ex: The program asks the user how much they want to deposit; program adds deposit amount to total balance.

Fairly new to coding so I know most of the basics (First semester in college) like arrays, structs and StreamReader and StreamWriter so pls no bully for lack of knowledge.

RBC002
Ariel Bendahan
1337
50000

^ Text file for reference

 StreamWriter myfilewrite = new StreamWriter("AccountInfo.txt");
            switch (choice)
            {
                case 1:
                    Console.Write("Entrez le montant à déposer : ");
                    atmFunctions.DepositAmount= Convert.ToInt32(Console.ReadLine());
                    while (atmFunctions.DepositAmount < 2 || atmFunctions.DepositAmount > 20000)
                    {
                        Console.Write("Entrez le montant à déposer (min $2 max $20,000) : ");
                        atmFunctions.DepositAmount= Convert.ToInt32(Console.ReadLine());
                    }
                    myfilewrite
                    *Stuck here; can't figure out what to put.*

                    DisplayTransaction(bankAccount.AccountNumber,bankAccount.Name,bankAccount.NIP,bankAccount.TotalBalance);
                    break;
            }

^ Code segement in which I'm stuck at

CodePudding user response:

If you are just trying to append a line to your file, then it should be as siimple as:

StreamWriter myfilewrite = new StreamWriter("AccountInfo.txt");
            switch (choice)
            {
                case 1:
                    Console.Write("Entrez le montant à déposer : ");
                    var amountToWrite = Console.ReadLine();
                    atmFunctions.DepositAmount= Convert.ToInt32(amountToWrite);
                    while (atmFunctions.DepositAmount < 2 || atmFunctions.DepositAmount > 20000)
                    {
                        Console.Write("Entrez le montant à déposer (min $2 max $20,000) : ");
                        amountToWrite = Console.ReadLine();
                        atmFunctions.DepositAmount= Convert.ToInt32(amountToWrite);
                    }
                    myfilewrite.Write(amountToWrite);

                    DisplayTransaction(bankAccount.AccountNumber,bankAccount.Name,bankAccount.NIP,bankAccount.TotalBalance);
                    break;
            }

Just call .Write() on your StreamWriter and pass it the string you want to append to the file.

CodePudding user response:

I fixed my issue by adding the deposit amount to the total balance, then using StreamWriter to re-write the entire file and the new total balance. I am very sorry if I wasted anyone's time due to me forgetting what my teacher taught me.

  • Related