Code not working as it should

Hello. I made a code that should make an text file and store language name in it. And it works, it makes a file, and writes language in, but when i want to load this file and read language in another scene, it doesnt work. Here is a piece of script and how i use it:

public void Start ()

 {
     StreamReader r = File.OpenText(Application.persistentDataPath + "//" + "jezyk.txt");
     string jez = r.ReadToEnd ();
     r.Close();
     jezyk = jez;
     if (jezyk.Equals ("polish")) {
         guzik1.GetComponentInChildren<Text> ().text = "Szybka gra";
     } else if (jezyk.Equals ("english")) {
         guzik1.GetComponentInChildren<Text> ().text = "Quick game";
     } else if (jezyk.Equals ("russian")) {
         guzik1.GetComponentInChildren<Text> ().text = "Быстрая игра";
     }

Well, as i said guessed in my comment you’re using WriteLine. WriteLine does write an additional carriage return + line feed at the end of the text. So the file doesn’t only contain the text you’ve written into but also the new line characters. When you do ReadToEnd() you actually read in the whole file which includes the new line characters. That’s why i suggested to print the string length as well. The string length should tell you if the character count is right.

Furthermore you actually overwrite your text file before you read it because you have those lines in front of the reading code:

StreamWriter w;
w = f.CreateText();    
w.Close ();

Those lines will create a new text file that will overwrite the existing file, so you end up with an empty file.

To avoid all those issues you could simply use File.WriteAllText and File.ReadAllText. Those two methods will write (and overwrite if necessary) the whole file and read the whole file.

// write
File.WriteAllText(Application.persistentDataPath + "//" + "jezyk.txt", "polish");


// read
string jez = File.ReadAllText(Application.persistentDataPath + "//" + "jezyk.txt");

There’s no need for deleting the file if you just want to overwrite it.

Instead of writing a file with a single word in it you could simply use PlayerPrefs.

// write
PlayerPrefs.SetString("language", "polish")

// read
string jez = PlayerPrefs.GetString("language", "english");

GetString takes a “key” and a default value in case “language” doesn’t exist yet.