How to get the next file in a directory?

I have a directory of files, with one of them currently in use by the scene. I have an array of all the files in the directory (using DirectoryInfo.GetFiles) and the name of the current file. I’m trying to find the index of the current file in that array and then increment to get the next file.

I currently have this:

#pragma strict

function LoadNext(){
	var currentEvent = PlayerPrefs.GetString("File To Load");
	var dir = new DirectoryInfo(Application.streamingAssetsPath);
	var filesInfo = dir.GetFiles("*.json");

	var currentFile = dir.GetFiles(currentEvent)[0];
	var currentIndex = filesInfo.IndexOf(filesInfo, currentFile);
	
	if(currentIndex + 1 == filesInfo.length){
		//no more files!
		Debug.Log("No more files!");
	}
	else if(currentIndex == -1){
		//don't know where we are. did File To Load not get set?
		Debug.Log("file not found!");
	}
	else{
		PlayerPrefs.SetString("File To Load", filesInfo[currentIndex + 1].Name);
		Debug.Log("loading file " + PlayerPrefs.GetString("File To Load"));
		//the file is loaded elsewhere. All that script needs is the name of the new file.
	}
}

I’ve tried various ways to get the index, but everything I try fails to find the file and returns -1. Is there something I’m missing?

I believe filesInfo.IndexOf will always return -1 as you are not comparing items from the same list.

dir.GetFiles(“*.json”); will return a list of files.
dir.GetFiles(CurrentEvent)[0] will return a different list of files, even if it contains the exact same files, it won’t be the same object.

You should instead iterate from filesInfo until you find currentFile, by comparing their ‘.Name’ property.