Thursday, August 6, 2009

Get a recursive list of files in a given directory

Here is a simple code snippet:

using System.Collections.Generic;
usingSystem.IO;
usingSystem.Text;

. . .

static void Main(string[] args)
{
List<FileSystemInfo> fileInfo = GetDirectoryInfo(@"c:\temp", true);
StringBuilder directoryCsv = new StringBuilder();
directoryCsv.Append("Name,Full Name,Parent Folder,Creation Time,Last Access Time,Last Write Time,Length, Extension,Attributes\r\n");
foreach (FileSystemInfo di in fileInfo)
{
if (di.GetType() == typeof(FileInfo))
{
directoryCsv.Append(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}\r\n", di.Name, di.FullName, di.FullName.Replace(di.Name, ""), di.CreationTime, di.LastAccessTime, di.LastWriteTime, ((FileInfo)di).Length.ToString(), di.Extension, di.Attributes.ToString()));
}
else
{
directoryCsv.Append(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}\r\n", di.Name, di.FullName, di.FullName.Replace(di.Name, ""), di.CreationTime, di.LastAccessTime, di.LastWriteTime, "", "", di.Attributes.ToString()));
}
}
SaveCsvFile(directoryCsv.ToString(), @"c:\temp\test.csv");
}
public List<FileSystemInfo> GetDirectoryInfo(string directoryPath, bool includeDirectoryInfo)
{
List<FileSystemInfo> directoryList = new List<FileSystemInfo>();
DirectoryInfo di = new DirectoryInfo(directoryPath);
foreach (DirectoryInfo childDi in di.GetDirectories())
{
directoryList.AddRange(GetDirectoryInfo(childDi.FullName, includeDirectoryInfo));
}
if (includeDirectoryInfo)
{
directoryList.Add(di);
}
directoryList.AddRange(GetFileInfo(directoryPath));
return directoryList;
}

public List<FileSystemInfo> GetFileInfo(string filePath)
{
DirectoryInfo di = new DirectoryInfo(filePath);
FileInfo[] rgFiles = di.GetFiles("*.*");
List<FileSystemInfo> fileList = new List<FileSystemInfo>();
foreach (FileInfo fi in rgFiles)
{
fileList.Add(fi);
}
return fileList;
}
private void SaveCsvFile(string fileText, string fileName)
{
try
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "CSV Files (*.csv)|*.csv";
saveFileDialog1.FileName = fileName + ".csv";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(myStream);
wText.Write(fileText);
wText.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
 

Update:  I found a nice solution using LINQ for filtering on multiple file extensions.

http://msdn.microsoft.com/en-us/library/wz42302f.aspx

using System.Linq;

string folder = @"C:\Projects";

IEnumerable<string> fileNames =  Directory.GetFiles(folder).Where(f => f.EndsWith( ".vb" ) || f.EndsWith( ".xml" ) || f.EndsWith( ".aspx" ));

No comments:

Post a Comment