- Home /
How to append a string to a file if the file exists
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?
The code i'm using is:
string tmp = string.Format ("DATE: {0} \r\n PLAYER: {1} TIME: {2} POSITION: {3}", System.DateTime.Now, data.id, data.score, DataStorage.instance.posTxt.text);
if (File.Exists (Application.persistentDataPath + "/" + data.id + ".dat")) {
File.AppendAllText (Application.persistentDataPath + "/" + data.id + ".dat", tmp);
} else {
File.Create (Application.persistentDataPath + "/" + data.id + ".dat");
StreamWriter sr = File.Open(Application.persistentDataPath + "/" + data.id + ".dat",FileMode.Open);
sr.WriteLine (tmp);
sr.Close ();
}
Thank you all in advance
Comment
Answer by sys12 · Sep 16, 2015 at 12:15 PM
yes!! thank you very much sys12! that's what i was looking for
Answer by codemaker2015 · Oct 16, 2021 at 02:52 PM
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);
}
}
}