Get next file in the folder

4.3k views Asked by At

When you open a picture in Windows Photo Viewer, you can navigate backward and forward between supported files using arrow keys (next photo / previous photo).

The question is: how to get path of the next file given path of the current file in the folder?

2

There are 2 answers

2
Selman Genç On

You can do this easily by getting all paths into a collection and keep a counter.If you don't want to load all file paths into memory you can use Directory.EnumerateFiles and Skip method to get next or prev 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;
}

Ofcourse you need some additional checks, for example in NextFile you need to check if you get to the last file, you need to reset the counter, likewise in the PreviousFile you need to make sure counter is not 0, if so return the first file etc.

1
Vikas Gupta On

Given your concern with large number of files in a given folder, and desire to load them on demand, I'd recommend the following approach -

(Note - The suggestion of calling Directory.Enumerate().Skip... in the other answer works, but is not efficient, specially so for directories with large number of files, and few 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 a linked list, as the user moves to next file. The logic will essentially look like this -

  1. Use the linked list for your previous and next navigation.
  2. On initial load or click of Next, if the linked list, or its next node is null, then use the GetNextFile method above, to find the next path, display on UI, and add it to the linked list.
  3. For Previous use the linked list to identify the previous path.