在Windows照片查看器中打开图片时,可以使用箭头键在支持的文件之间来回导航(下一张照片/上一张照片)。
问题是:在给定文件夹中当前文件的路径的情况下,如何获取下一个文件的路径?
您可以通过将所有路径放入集合并保留一个计数器来轻松实现这一点。如果您不想将所有文件路径加载到内存中,可以使用Directory.EnumerateFiles
和Skip
方法来获取下一个或上一个文件。例如:
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;
}
当然,您需要一些额外的检查,例如在NextFile
中,您需要检查是否到达最后一个文件,您需要重置计数器,同样在PreviousFile
中,您也需要确保计数器不是0
,如果是,则返回第一个文件等。
考虑到您对给定文件夹中大量文件的担忧,并希望按需加载这些文件,我建议使用以下方法-
(注意-在另一个答案中调用Directory.Enumerate().Skip...
的建议是有效的,但效率不高,尤其是对于文件数量大的目录,其他原因很少)
// 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.
编辑:当用户移动到下一个文件时,可以在链接列表中跟踪以前的文件。逻辑基本上看起来是这样的-
- 使用链接列表进行上一次和下一次导航
- 在初次加载或单击
Next
时,如果链表或其下一个节点为空,则使用上面的GetNextFile
方法查找下一个路径,显示在UI上,并将其添加到链表中 - 对于
Previous
,请使用链接列表来标识以前的路径