- Home /
Why data will be overwrite in the file
This is working fine but i realise that the file will be overwrite every time a new game is play which is not i want. I want to maintain the data. Instead of overwrite the data, i want to add on to the data. Any thing bother me is regarding, how we know this file is belong to which players. Is it any possible way i can solve this issues? Like this data in this file is the record play by may.. Please help!!! :((
using UnityEngine;
using System.Collections;
using System;
using System.Text;
using System.IO;
public class Monitor : MonoBehaviour {
String path;
String fileName;
String playerName;
int id =1;
// Use this for initialization
void Start ()
{
fileName = "/Monitoring.txt";
playerName = playerControl.playerName;
print(gameControl.previousWord1);
}
// Update is called once per frame
void Update ()
{
//string messageToAccess = gameControl.previousWord1;
path = Application.dataPath + fileName;
using(FileStream fs = File.Create(path))
{
AddText(fs, "PlayerName: " + playerName);
AddText(fs, "\r\n================================");
AddText(fs, "\r\n" + id);
for(int j = 0; j < gameControl.radical00Store.length; j++)
{
AddText(fs, "\t" + gameControl.radical00Store[j]);
AddText(fs, "\t" + gameControl.radical0Store[j]);
AddText(fs, "\t" + gameControl.previousWord1[j]);
}
AddText(fs, "\t" + gameControl.wrongMatch + "\n");
}
id++;
//Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
}
private static void AddText(FileStream fs, string value)
{
byte[] info = new UTF8Encoding(true).GetBytes(value);
fs.Write(info, 0, info.Length);
}
}
Answer by Owen-Reynolds · Mar 31, 2012 at 03:53 AM
Look at File.Open
(instead of create.) It has an Append option to add to the end. But, in practice, you rarely want to write to the end - you want to modify what's there. To do that, read the file into an array make changes (like add 1 to games played,) then erase the old file and write it all back.
For names, you can make the name part of the fileName: MonitoringStan.txt
, and have 1 file for each player. Most people would have one file look like: name, stats for name; 2nd name, stats for 2nd name; ... . Then have the reader and writer know to keep reading/writing names until EOF.
Hi Owen, thank for the answer. Are you able to provide some code snippet??
Your answer
![](https://koobas.hobune.stream/wayback/20220613065739im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Can not save data to file and then load it in Unity3d 2 Answers
3 Arrays of data write to file and then display to player 0 Answers
Best way to store and access info in long txt files? 0 Answers
Writing Vector3 on a text file 2 Answers
File.Seek called by AudioSource.PlayDelayed takes too long to run if it built as APK. 0 Answers