Hello all,
I want to get data to a .txt file when the game finishes.
But the file might already be created, so i want to append the new line.
(I have been searching and i haven’t found the right way to do it)
Can you please help me?
Try the following code to create and write content to a text file in Unity3D.
void CreateLog() {
string timestamp = DateTime.Now.ToString("dd-mm-yyyy_hh-mm-ss");
PlayerPrefs.SetString("timestamp", timestamp);
string path = Application.persistentDataPath + "/" + "log_" + timestamp + ".txt";
// This text is added only once to the file.
if (!File.Exists(path)) {
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(DateTime.Now.ToString() + ": " + "App initialised");
}
} else {
// This text is always added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = File.AppendText(path)) {
sw.WriteLine(DateTime.Now.ToString() + ": " + "App initialised");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path)) {
string line = "";
while ((line = sr.ReadLine()) != null)
{
Debug.Log(line);
}
}
}