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();
}
Calling Function:
string lastFile = GetLastFileInDirectory("C:\\Temp", "*.*");
{
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();
}
Calling Function:
string lastFile = GetLastFileInDirectory("C:\\Temp", "*.*");
View comments