以上两个答案都有空目录的问题。这是一个检查空目录和不存在目录的混合答案。
/// <summary>
/// Returns most recently written Filename from the specified directory.
/// If the directory does not exist or doesn't contain any file, null is returned.
/// </summary>
/// <param name="directoryInfo">Path of the directory that needs to be scanned</param>
/// <param name="filePattern">Search Pattern for file</param>
/// <returns></returns>
public static string NewestFileInDirectory(string directoryPath, string filePattern)
{
DirectoryInfo directoryInfo = new DirectoryInfo(directoryPath);
if (directoryInfo == null || !directoryInfo.Exists)
{
return null;
}
var minTime = DateTime.MinValue;
string newestFile = null;
foreach (var file in Directory.GetFiles(directoryPath, filePattern))
{
var fileLastWriteTime = File.GetLastWriteTimeUtc(file);
if (fileLastWriteTime > minTime)
{
minTime = fileLastWriteTime;
newestFile = file;
}
}
return newestFile;
}