[英]Hiding hidden documents and excluding file extensions from a directory in C#
我在互聯網上搜索並找到了一些解決方案,但對於我來說它們似乎不起作用,我也不知道為什么。 我列出了工作目錄中所有的.xls文件。 現在,由於我使用的是Office的較早版本,因此我希望排除.xlsx文件以及所有臨時文件,但這似乎不起作用。 我試過了:
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();
現在,由於沒有“ fileAtrribute”,我沒有第一行就使用“ name.Attributes”進行了嘗試,但是他找不到它。 我也嘗試搜索“?.xls”,但是他沒有列出任何文件。 我究竟做錯了什么?
您有以下邏輯問題:
string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
.Where(name => !name.EndsWith(".xlsx") || !name.Contains(@"\~$")
|| (fileAttribute & FileAttributes.Hidden) == 0).ToArray()
你要和,而不是
string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
.Where(name => !name.EndsWith(".xlsx") && !name.Contains(@"\~$")
&& (fileAttribute & FileAttributes.Hidden) == 0).ToArray()
但是,您的文件屬性正在檢查目錄,而不是文件。
所以你實際上想要
string[] filePaths = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.xls")
.Where(name => !name.EndsWith(".xlsx") && !name.Contains(@"\~$")
&& (File.GetAttributes(name) & FileAttributes.Hidden) == 0).ToArray()
您有幾個問題。 首先,您的||
的應該是&&
。 您想排除名稱不以xlsx結尾並且不包含〜$並且不隱藏的文件。
其次,對隱藏屬性的檢查看起來不正確。 當前,您正在獲取文件夾的屬性,然后將其與每個文件進行比較。 您確實要獲取每個文件的屬性。
總之,您需要:
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和臨時文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.