Hello Sir,
just how i would approach this:
(and sorry if some capital letters are mixed up, autocorrection is a mess)
as you have given few Information about how you store / save your files and how you would like to read them i start at 0
First, lets create a model for our files
[System.Serializable]
public class FileModel
{
public int Score { get; set; }
public string TeamName { get; set; }
}
Note the Serializable Attribute - we will Need it later for the binaryformatter
now lets assume we are in some Method (for sake of discussion in the start())
void Start () {
var path = Path.Combine(Application.streamingAssetsPath, @"DataFiles\");
BinaryFormatter bf = new BinaryFormatter();
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
we Setup a path where we would like to store our files (note here that you have to use the streamingassetpath as otherwise after a build your path would not work)
and a binaryformatter object (for later use ((using System.Runtime.Serialization.Formatters.Binary;)
now lets write a method that stores your data
public void SaveToDisk(FileModel model, string path)
{
BinaryFormatter bf = new BinaryFormatter();
using (FileStream fs = File.OpenWrite(path + "\\" + model.TeamName + ".dat"))
{
bf.Serialize(fs, model);
}
}
As you can see the method would get a model for your data and a path to store it - the filestream would write what it gets from the binaryformatter in given file / path
so let’s go back to our start method and try and read them again → to store them in an Array (because that’s what this is about right?)
.
.//add in Start()
.
var model = new FileModel() { Score = 100, TeamName = "AnyName" };
var model2 = new FileModel() { Score = 210, TeamName = "SomeName" };
SaveToDisk(model, path);
SaveToDisk(model2, path);
//we simply created two test objects and save them
//let's get the Directory (using System.IO)
DirectoryInfo di = new DirectoryInfo(path);
//Now get all files from this Directory - and let's filter them by their fileextension
//I used System.Linq here - of Course you can do in other ways
var files = di.GetFiles().Where(o => o.Name.EndsWith(".dat")).ToArray();
//now we create our Array of fileModels - the size of it is simply the amount of files we have in our Directory which match certain criteria (fileextension here)
var AllFiles = new FileModel[files.Length];
//For every file we now use the binaryformatter to get back our data and store it in our Array as a filemodel so we can easily work with the data again
for (int i = 0; i < files.Length; i++)
{
using (FileStream fs = File.OpenRead(files[i].FullName))
{
Debug.Log(files[i].FullName);
AllFiles[i] = (FileModel)bf.Deserialize(fs);
}
}
//Just a testmessage to see if it worked
Debug.Log(AllFiles[0].Score);
Debug.Log(AllFiles[1].Score);
hope this helps and is what you asked for
greetings