loading all json files in a folder

What is the best way to load all the Json files in folder without calling each one by name?

I mean… to load a file you need to have its name.

If you mean without hard coding their names… you can get all the files in a folder with either Directory.GetFiles, or Directory.EnumerateFiles:

Note both take an optional search pattern to filter the files (so like *.json is all files ending in .json).

Then load each one individually however you like. File.ReadAllText, FileStream, StreamReader, whatever.

My issue is. I am downloading models at runtime then serializing them. When serializing them I am adding the model name to the file name…but when a user is using it in the field they will not know what all the model names will be.

I was wondering how I would use *_geo.json" but not sure how to do that.

I am storing the json files with this:

string filename = Path.Combine(Application.persistentDataPath, modelFileNmae + SAVE_FILE);

The “SAVE_FILE” is the "geo.json and the modelFileNmae is the models name.

Did you try Directory.EnumerateFiles or Directory.GetFiles with *_geo.json as your filter?

Cause it should work.

Just use Application.persistentDataPath as the directory you’re looking in. Like so:

foreach(var file in Directory.EnumerateFiles(Application.persistentDataPath, "*_geo.json"))

Note, you’ll need to be “using” the System.IO namespace.

1 Like

Trying to figure it out now.

Is it going to step through each one individually or all at once?

It’s a foreach loop, the loop will step through the iteration of the entire thing.

EnumerateFiles is an enumerable and enumerates one by one. GetFiles returns an array which can be enumerated.

Would adding each file name to an array and serializing that then step through them on restart work you think?

I got it to work. Thanks dude. I’ll need to fine tune it though.