Z
Z
Zimaell2021-02-23 20:38:01
Unity
Zimaell, 2021-02-23 20:38:01

How to safely overwrite a file?

Here I have a file in /Resources/Data/DataSettings.txt file, it contains settings as a string separated by "|", that is, I get it to read like this

public float MusicVolume = 0.2f; // по умолчанию
public float SoundVolume = 0.2f; // по умолчанию
public int Language = 0; // по умолчанию
private void GetDataVariable(){
  TextAsset DataSettings = Resources.Load("Data/DataSettings") as TextAsset;
  string StringSettings = DataSettings.text.Replace(" ", "");
  string[] ArrayStringSettings = StringSettings.Split('|');
  string name,value;
  foreach(string val in ArrayStringSettings){
    if(!val.Contains("=")) continue;
      string[] a = val.Split(new string[] {"="}, StringSplitOptions.RemoveEmptyEntries);
      name = a[0];
      value = a[1];
      switch(name){
        case "MusicVolume": MusicVolume = float.Parse(value, CultureInfo.InvariantCulture); break;
        case "SoundVolume": SoundVolume = float.Parse(value, CultureInfo.InvariantCulture); break;
        case "Language": Language = Convert.ToInt32(value); break;
        }
      }
........... и т.д.

the file itself looks like this
MusicVolume = 0.6|SoundVolume = 0.2|Language = 3

Question 2:
1 - How to overwrite it?
And then this is how it adds and does not rewrite
StreamWriter writer = new StreamWriter("Assets/Resources/Data/DataSettings.txt", true);
writer.WriteLine("........");
writer.Close();

2 - How to overwrite safely?
And then suddenly the overwriting goes as follows (as many advise on the Internet), delete the file, create a new one and fill it in ....
But it may be that it will be deleted and the application will close and the bb data ...
How to make these actions more correct ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Karbivnichy, 2021-02-23
@Zimaell

StreamWriter writer = new StreamWriter("Assets/Resources/Data/DataSettings.txt", true);

true - new data is added to the end of the file, false - the file is overwritten.
And then suddenly the overwriting goes as follows (as many advise on the Internet), delete the file, create a new one and fill it in ....

MSDN - How to: Write text to a file - everything is well told and shown with examples.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question