Hi all i’ve got the following code which will go off and get all files from a route directory, including sub directories, when certain criteria are matched. Currently i have two methods; one to go get all the files and add them to a List and then another method to return the List. Just wondering if this is the best way to do it or is it more efficient to combine the two? Or can my code be re-written to be more efficient? Sorry i’m quite new to all this!
public class FileUtility
{
List<FileInfo> fileInfoList = new List<FileInfo>();
public void ProcessDir(string sourceDir, String userName)
{
try
{
string userNameFirstLetter = userName.First().ToString();
DirectoryInfo di = new DirectoryInfo(sourceDir);
foreach (FileInfo fi in di.GetFiles())
{
if (fi.Extension == ".xls" || fi.Extension == ".xlsx" || fi.Extension == ".pdf")
{
if (fi.Name.Contains(userName))
{
if (fi.Name.Contains("X"))
{
if(fi.Name.First().ToString().Equals(userNameFirstLetter))
{
if (fi.Name.Split(Convert.ToChar("X"))[0].Equals(userName))
{
fileInfoList.Add(fi);
}
}
}
}
}
}
// Recurse into subdirectories of this directory.
string[] subdirEntries = Directory.GetDirectories(sourceDir);
foreach (string subdir in subdirEntries)
{
// Do not iterate through reparse points
if ((File.GetAttributes(subdir) & FileAttributes.ReparsePoint) != FileAttributes.ReparsePoint)
{
ProcessDir(subdir, userName);
}
}
}
catch (DirectoryNotFoundException exp)
{
throw new DirectoryNotFoundException("Directory not found " + exp.Message);
}
catch (IOException exp)
{
throw new IOException("The Process cannot access the file because it is in use by another process " + exp.Message);
}
}
public List<FileInfo> GetFileInfoList()
{
return fileInfoList;
}
}
You can do something like this:
Then you can use
LINQto filter this down if you’re using C# 3.5 or above which I assume you are. Something like:Or combine the 2: