I have a MySQL table with a list of file name. I would like to get a list of all file in a directory only if their names are not present in the table.
I can put the list of the database's file in a Datatable and write something like:
string[] files = Directory.GetFiles(directory);
foreach (Datarow row in dataTable.Rows)
for (int i=0; i<files.Length; i++)
if (row[0].equals(files[i]) {
files[i].delete();
break;
}
The upper code is only a pseudo-example. Can't I directly use Directory.GetFiles(directory) by specifying a filter in order to don't write all the iteraction?
please find code snippet below
decided to do it in steps - to have more maintainable code
void Main()
{
// given a list of files from db
DataTable dataTable = new DataTable("x");
dataTable.Columns.Add("file", typeof(string));
dataTable.Rows.Add("HaxLogs.txt");dataTable.Rows.Add("swapfile.sys");dataTable.Rows.Add("four.txt");
var directory = "c:\\";
var directoryFilesWithPaths = Directory.GetFiles(directory)
.Select( x=> new FileEntry { Path = x, FileName = Path.GetFileName(x)});
var directoryFiles = directoryFilesWithPaths.Select(x => x.FileName).ToList();
var filesList = (from DataRow dr in dataTable.Rows
select dr[0].ToString()).ToList();
var filesToProcess = directoryFiles.Except(filesList);
foreach (var file in filesToProcess)
{
// process file here
Console.WriteLine(file);
}
}