Jordan Paul
Jordan Paul

Reputation: 11

How to read and write to a text file with nothing in it

So im making a simple register and login in unity and ive came across a wall. My code works fine if it has any character or word in it but with it blank the loop doesnt work because it is a while line != null. I know that is the problem but i dont know any other loops to use in this scenario. Im using streamreader so i can constantly update the file as i can close it.

v

    if (Input.GetKeyDown(KeyCode.Return))
    {
        StreamReader sr = new StreamReader("C:/Users/jorda/OneDrive/2D GAME REMAKE/Assets/login.txt",true);
        line = sr.ReadLine();


        while (line != null)
        {
            change =false;

            if (line == Logdetails)
            {
                Debug.LogWarning("Account already exists");
                username.GetComponent<InputField>().text = "";
                password.GetComponent<InputField>().text = "";
                break;

            }
            else if (Username == "" || Password == "")
            {
                Debug.LogWarning("There is an empty field");
                break;
            }
            else 
            {
                change = true;
            }
            line = sr.ReadLine();
        }//while loop ends
        sr.Close();
        if (change == true)
        {
            Write();
        }
    }

public void Write() {

    StreamWriter sw = new StreamWriter("C:/Users/jorda/OneDrive/2D GAME REMAKE/Assets/login.txt", true);
    {
        sw.WriteLine(Logdetails);
        username.GetComponent<InputField>().text = "";
        password.GetComponent<InputField>().text = "";
        sw.Close();
        SceneManager.LoadScene(1);
    }
}

Upvotes: 1

Views: 238

Answers (1)

Matt
Matt

Reputation: 183

Use a do while loop, which makes sure the code runs at least once, meaning for empty files one of your else branches is executed:

do
{
  change =false;

  if (line == Logdetails)
  {
    ...
  }
  ...
}
while(line != null)

Upvotes: 2

Related Questions