Monday, December 29, 2014

C# Find Most Recent File In Directory

public string GetLastFileInDirectory(string directory, string pattern = "*.*")
{
if (directory.Trim().Length == 0)
return string.Empty; //Error handler can go here

if ((pattern.Trim().Length == 0) || (pattern.Substring(pattern.Length - 1) == "."))
return string.Empty; //Error handler can go here

if (Directory.GetFiles(directory, pattern).Length == 0)
return string.Empty; //Error handler can go here

//string pattern = "*.txt"

var dirInfo = new DirectoryInfo(directory);
var file = (from f in dirInfo.GetFiles(pattern) orderby f.LastWriteTime descending select f).First();

return file.ToString();
}

No comments:

Post a Comment