简体   繁体   中英

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?

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()

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();

由于调用Directory.GetFiles(Directory.GetCurrentDirectory(),“ *。xls”),您已经排除了.xlsx和临时文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM