user4671342
user4671342

Reputation:

Hiding hidden documents and excluding file extensions from a directory in C#

I was searching around the internet and found some solutions but they don't seem to work in my case and I don't know why. I list all files in the working directory which are .xls files. Now since I'm working with an older version of Office I want to exclude the .xlsx files and also all temporary files but this doesn't seem to work. I tried:

 FileAttributes fileAttribute = File.GetAttributes(Directory.GetCurrentDirectory());

   string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
   .Where(name => !name.EndsWith(".xlsx") || !name.Contains(@"\~$") 
   || (fileAttribute & FileAttributes.Hidden) == 0).ToArray();

Now I tried it without the first line and with " name.Attributes " since " fileAtrribute "but he can't find it. I also tried to search for "?.xls" but then he doesn't list any files. What am I doing wrong?

Upvotes: 0

Views: 238

Answers (3)

petelids
petelids

Reputation: 12815

You have a couple of issues. Firstly, your ||'s should be &&'s. You want to exclude files where the name doesn't end with xlsx AND it doesn't contain ~$ AND where it's not hidden.

Secondly, your check for the hidden property looks incorrect. Currently you are grabbing the attributes of the folder and then comparing that with each file. You really want to get the properties of each file.

In summary, you need:

string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
.Where(name => !name.EndsWith(".xlsx") && !name.Contains(@"\~$")
&& (File.GetAttributes(name) & FileAttributes.Hidden) == 0).ToArray();

Upvotes: 1

BugFinder
BugFinder

Reputation: 17868

You have a logic issue with:

string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
   .Where(name => !name.EndsWith(".xlsx") || !name.Contains(@"\~$") 
   || (fileAttribute & FileAttributes.Hidden) == 0).ToArray()

you want ands, not ors..

string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
   .Where(name => !name.EndsWith(".xlsx") && !name.Contains(@"\~$") 
   && (fileAttribute & FileAttributes.Hidden) == 0).ToArray()

However, your fileattribute is checking the directory, not the file.

So you actually want

string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
   .Where(name => !name.EndsWith(".xlsx") && !name.Contains(@"\~$") 
   && (File.GetAttributes(name) & FileAttributes.Hidden) == 0).ToArray()

Upvotes: 2

Paweł Mikołajczyk
Paweł Mikołajczyk

Reputation: 381

Since you call Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls") you have already excluded .xlsx and temporary files.

Upvotes: 0

Related Questions