Code meant for Unity, but could work the same for normal C# as no essential code is Unity specific, just the "Debug.Log" and "Application.persistentDataPath".
The read function returns an Array of strings.
The write function needs an Array of strings to write to the text-file.
PS: The Update/Version Check uses Unitys Remote Config (https://www.youtube.com/watch?v=14njHI4CGgA&t=156s).
//Read .txt File
private string[] getDataFromFile(string fileName = "SaveManager")
{
string line;
//Pass the file path and file name to the StreamReader constructor
Debug.Log("Path: " + Application.persistentDataPath + "/" + fileName + ".txt");
checkTextFileExists();
StreamReader file = new StreamReader(Application.persistentDataPath + "/" + fileName + ".txt");
if(!File.Exists(Application.persistentDataPath + "/" + fileName + ".txt"))
{
Debug.LogError("File doesn't exist.");
return null;
}
else
{
//instatiates the temporary List list
List<string> list = new List<string>();
try
{
//Read the first line of text
line = file.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//add the new line to the List
list.Add(line);
//Read the next line
line = file.ReadLine();
}
//close the file
file.Close();
}
catch (Exception e)
{
Debug.LogError("Exception: " + e.Message);
}
//unloads the file
file.Close();
//turns the List list into an Array and returns it
return list.ToArray();
}
}
//You can turn a string into an int with int/float.Parse(string)
//You could also use Convert.ToInt()/.ToFloat()
//Write to .txt File
private void writeToFile(string[] data, string fileName = "SaveManager")
{
string path = Application.persistentDataPath + "/" + fileName + ".txt";
if (File.Exists(path))
{
File.Delete(path); // deletes the file, if it already exists
}
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < data.Length; i++)
{
sw.WriteLine(data[i]);
}
sw.Close();
}
}
0 comments