HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

One-by-one file deletion for a derived list of files

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
filelistonefilesfordeletionderived

Problem

I have the following C# code for deleting files from a folder (and from its sub folders) excluding a list of files specified in an Excel file. The code works fine.

The deletion is happening one-by-one in a for loop. Is there a way to improve its performance by reducing the time taken for deletion?

```
class Program
{
public static List AllFilesStaticList = new List();

static void Main(string[] args)
{

string locationOfExcelList = @"G:\Test1\ExclusionList.xls";
string sheetName = "List$";
string sourceDirectory = @"G:\TFS2\";

List excludeList = Import_To_DataTable_FromExcel(locationOfExcelList, sheetName);
ProcessAllDirectoryToGetFileList(sourceDirectory);

//Get files to be deleted (Items that are not present in excludeList)
List eligibleListToProcess = AllFilesStaticList.Where(x => !excludeList.Any(y => x.Contains(y))).ToList();

//Iterating two lists - need to be improved
foreach (string fileEntry in eligibleListToProcess)
{
try
{
if (File.Exists(fileEntry))
{
//foreach delete need to be made more efficient
File.Delete(fileEntry);
Console.WriteLine(fileEntry);
}
}
catch
{
//Hide the exception for now
}
}
Console.ReadLine();
}

// Process all files in the directory passed in, recurse on any directories
// that are found, and process the files they contain.
public static void ProcessAllDirectoryToGetFileList(string targetDirectory)
{
// Process the list of files found in the directory.
//Get files with their path
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
AddFile(fileName);
}

// Recurse into subdirectories of th

Solution

I may suggest the following : why checking for file deletion ?

if (File.Exists(fileEntry))


After all, in file.delete documentation we have :


If the file to be deleted does not exist, no exception is thrown.

Code Snippets

if (File.Exists(fileEntry))

Context

StackExchange Code Review Q#139463, answer score: 5

Revisions (0)

No revisions yet.