I\'m writing a C# programlet to crawl a directory and give me a listing of files whose date in the last CSV line is less than the current date. Since this is a programlet, I\'m
Based on "programlet to crawl a directory and give me a listing of files whose date in the last CSV line is less than the current date. Since this is a programlet, I'm not really spending too much time making the code very clean or anything" I propose something similar to the following which I've used in the past. Take it or leave it.
What it does: Specify a root directory, function gets all files within directory of given type (for your time requirement, modify files.add(...) to match your criteria)
Only leaving this here as an alternative to your work since you said you don't want to spend much time on it.
var data = GetAllFilesOfType('c:\rootpath', 'csv')
///
/// Gets files of specified type and appends them to the file list.
///
/// Starting file path
/// File type - Do not include prefix ('txt' instead of '*.txt
/// Returns results of WalkDirectoryTree
public static IEnumerable GetAllFilesOfType(string basepath, string type)
{
var root = new DirectoryInfo(basepath);
return WalkDirectoryTree(root, type);
}
///
/// Recursively gets all files from a specified basepath (provided by GetAllFilesOfType)
/// and appends them to a file list. This method reports all errors, and will break on
/// things like security errors, non existant items, etc.
///
/// Initially specified by calling function, set by recursive walk
/// File type that is desired. Do not include prefix ('txt' instead of '*.txt')
///
private static List WalkDirectoryTree(DirectoryInfo root, string type)
{
var files = new List();
//Traverse entire directory tree recursively - Will break on exception
var subDirs = root.GetDirectories();
foreach (var data in subDirs.Select(dirInfo => WalkDirectoryTree(dirInfo, type)).Where(data => data.Count > 0))
{
files.AddRange(data);
}
//If any file is found, add it to the file list
if (root.GetFiles(string.Format("*.{0}", type)).Length > 0)
{
files.Add(root.GetFiles(string.Format("*.{0}", type)));
}
//Kicks the file list up a level until it reaches root, then returns to calling function
return files;
}