Get next file in folder
You can do this easily by getting all the paths to the collection and saving the counter. If you don't want to load all file paths into memory, you can use the method Directory.EnumerateFiles
and Skip
to get the next or previous file For example:
int counter = 0;
string NextFile(string path, ref int counter)
{
var filePath = Directory.EnumerateFiles(path).Skip(counter).First();
counter++;
return filePath;
}
string PreviousFile(string path, ref int counter)
{
var filePath = Directory.EnumerateFiles(path).Skip(counter - 1).First();
counter--;
return filePath;
}
Of course, you need additional checks, for example, in NextFile
you need to check if you get to the last file, you need to reset the counter, similarly in PreviousFile
you need to make sure that the counter is not 0
, if so, it returns the first file, etc.
source to share
Given your concern about the large number of files in a given folder and wanting to download them on demand, I would recommend the following approach -
(Note: The invocation suggestion Directory.Enumerate().Skip...
in the other answer works, but is ineffective, especially for directories with a lot of files and several other reasons).
// Local field to store the files enumerator;
IEnumerator<string> filesEnumerator;
// You would want to make this call, at appropriate time in your code.
filesEnumerator = Directory.EnumerateFiles(folderPath).GetEnumerator();
// You can wrap the calls to MoveNext, and Current property in a simple wrapper method..
// Can also add your error handling here.
public static string GetNextFile()
{
if (filesEnumerator != null && filesEnumerator.MoveNext())
{
return filesEnumerator.Current;
}
// You can choose to throw exception if you like..
// How you handle things like this, is up to you.
return null;
}
// Call GetNextFile() whenever you user clicks the next button on your UI.
Edit: Previous files can be tracked in the linked list as the user navigates to the next file. The logic would look something like this:
- Use a linked list for your previous and next navigation.
- On boot or click
Next
, if the linked list or next node is null, use the above methodGetNextFile
to find the next path, display in the UI, and add it to the linked list. - To
Previous
use a linked list to identify the previous path.
source to share