Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi,
I have ten files in directory main
for example: fileA.xlsx, fileB.xlsx, FileC.xlsx, testFile.xlsx are all in Main directory
i want to archive and delete these files except the testFile.xlsx.
testFile should stay in the directory Main.

Will appreciate your help
Posted

1 solution

I dont even know if this will compile (Im on my Mac at the moment) - but I'd be trying something like

// Needs uses System.IO;

string folderPath = "Your File Folder Here";

if (Directory.Exists(folderPath))
{
	DirectoryInfo di = new DirectoryInfo(folderPath);

     // Get only the xlsx files excluding One We Don’t Want
     List<string> xlsxFiles = di.GetFiles("*.xlsx")
                              .Where(file => !(file.Name.EndsWith("testFile.xlsx")))
                              .Select(file => file.Name).ToList();

	foreach (string filenameToDelete in xlsxFiles)
	{
                // Archive File Goes Here
                // Then Delete It 
		File.Delete(filenameToDelete);
	}
}
 
Share this answer
 
Comments
Ericajlili 4-Nov-15 20:46pm    
thank you, just for delete I had to combine path and filename
Garth J Lancaster 5-Nov-15 2:34am    
no worries - I thought about that and didnt have time to go back and edit it - I hope you did it correctly, with Path.Combine(folderPath, filenameToDelete) :-)
Garth J Lancaster 5-Nov-15 2:37am    
btw - you could probably simplify this

.Where(file => !(file.Name.EndsWith(“testFile.xlsx”)))

to

.Where(file => file.Name != "testFile.xlsx")

since you're getting filenames without the full path

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900