1

I'm just trying to write a simple program that clears out my "Path" folder exept for 2 .exe files preselected. The problem is that I only succeed in deleting the first one (file1.exe). What am I doing wrong? Forgive me if I'm using the logical operators but in this moment is like my head is about to explode...

string[] filePaths = Directory.GetFiles(Path); foreach (string filePath in filePaths) { var name = new FileInfo(filePath).Name; name = name.ToLower(); if (name != "file1.exe" || name != "file2.exe") { File.Delete(filePath); } } 
1

2 Answers 2

3

Use && instead of || for your condition.

if (name != "file1.exe" && name != "file2.exe") 

You can also filter out the files with LINQ expression like:

var filePaths = Directory.GetFiles(Path) .Where(r=> !r.Equals("file1.exe", StringComparison.InvariantCultureIgnoreCase) && !r.Equals("file2.exe", StringComparison.InvariantCultureIgnoreCase)); 

and then you can do:

foreach (string filePath in filePaths) { File.Delete(filePath); } 
Sign up to request clarification or add additional context in comments.

5 Comments

It shouldn't. make sure your file is named as same as in the string for comparison.
When you do your string comparison, make sure you ignore case.
Also... add me as another vote for using && instead of ||
Yes thank you, it was an uppercase letter that was doing the trick!
Great... I'm glad the Stack Overflow community was able to help you. Since you're new, I'd like to remind you to close out this question by accepting an answer.
0

You are basically saying, if name is not equal to "file1.exe" OR name != "file2.exe" then delete a file path, the problem is you are using a OR logical operator so it only deletes one. Try using &&.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.