How to read specific line with Streamreader in c#?
Okay, im creating game for android and need make savesystem Im using C# so i dont wanna scripts in JS
Here is my script for save and load.. Im tried to make load system but nothing.. Save working ;D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using System.Timers;
public class SaveLoad : MonoBehaviour {
public int moneyo;
public int hrs;
public string date;
int workedhrs;
int savenumber;
public void SaveButton()
{
savenumber = savenumber + 1;
Save();
}
public void LoadButton()
{
Load();
}
void Save()
{
using (StreamWriter sw = new StreamWriter("savegame.txt"))
{
sw.WriteLine(""+moneyo.ToString());
sw.WriteLine(""+workedhrs.ToString());
sw.WriteLine("");
sw.WriteLine("Saved at:" + System.DateTime.Now);
Debug.Log("saved succesfuly");
sw.Close();
}
}
void Load()
{
using (TextReader rdr = File.OpenText("savegame.txt"))
{
string line;
while ((line = rdr.ReadLine()) != null)
Debug.Log(line);
rdr.Close();
}
}
}
And this is what i have in saved file:
0
0
Saved at:9/6/2017 5:33:02 PM
I wanna get info from first and 2nd line for get info about money and worked hrs in game
Please help me fast.
Answer by Iarus · Sep 06, 2017 at 05:10 PM
If your file format only contains these 3 lines, this should work.
void Load()
{
using (TextReader rdr = File.OpenText("savegame.txt"))
{
int lineIndex = 0;
string line;
while ((line = rdr.ReadLine()) != null)
{
if (lineIndex == 0)
moneyo = Int.Parse(line);
else if(lineIndex == 1)
workedhrs = Int.Parse(line);
lineIndex++;
}
rdr.Close();
}
}
Ok, im checking it now, i will write instantly if that works and if not ;P
In your code, the lineIndex++ is only done if lineIndex == 1. So you probably parse the first two lines with the first "if" and write in the moneyo variable twice. Then you parse the third line, it's not a number and the code crashes. Put the lineIndex after the "else if" block and it should work as expected.
... I should have used curly braces with the if else if blocks to make it more clear.
And i've got some stupid shit :/
Screens: http://screenshot.sh/m9nZiUN3Db$$anonymous$$ae http://screenshot.sh/n9GG$$anonymous$$RJ0l8XXk http://screenshot.sh/odyItkRfrsdoS
I don't know what is not working :/