Create a Score string . txt without overwriting the file

Asked

Viewed 500 times

0

The command written below does not create the score text. txt in the directory of the folder where the game is installed I also needed that the code below not overwrite the file but add the score below the already recorded points. C# Visual Studio Community 2017.

varexe = System.Environment.CurrentDirectory;


StreamWriter writer = new StreamWriter(varexe + "\\Score.txt");
                                                                    writer.WriteLine("Player1");
                                                                    writer.WriteLine(tent);
                                                                    writer.Close();

1 answer

1

You can use a File.Appendtext command, here you can find how to use it: Append Text C#

Code copied from the website I recommended

You choose between:

(1) Write to archive

(2) Add to file

(3) Only read the file

 using System;
 using System.IO;

class Test 
 {
   public static void Main() 
   {

     string path = @"c:\temp\MyTest.txt";
     // texto entra uma vez só no arquivo
     if (!File.Exists(path)) 
       {
        //(1) Criando o arquivo e escrevendo nele (Só de exemplo)
        using (StreamWriter sw = File.CreateText(path)) 
         {
            sw.WriteLine("Player1");
            sw.WriteLine("Pontos");
            sw.WriteLine("blablabla");
        }   
    }

    //(2) Aqui adiciona novas informações no texto no final da linha.
    using (StreamWriter sw = File.AppendText(path)) 
    {
            sw.WriteLine("Player1");
            sw.WriteLine("Pontos");
            sw.WriteLine("blablabla");
    }   

    //(3) Aqui abre o arquivo apenas para leitura
    using (StreamReader sr = File.OpenText(path)) 
    {
        string s = "";
        while ((s = sr.ReadLine()) != null) 
        {
            Console.WriteLine(s);
        }
    }
}
}   

I hope I helped you!

Browser other questions tagged

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