我的文件夹包含以下文件:
我想检查此文件夹中是否存在无关文件。例如,如果我在此文件夹中创建 examplefile.exe ,它必须给我一个错误,必须只有上面列出的文件。所以我创建了所需的文件字符串:
string[] only_these_files = {
"file1.exe",
"file2.dll"
};
现在我需要搜索无关的文件,但是如何?谢谢。
我尝试过此代码,但我不知道如何检查它。
string[] only_these_files = {
"image1.png",
"image2.png",
"image3.png",
"image4.png",
"image5.png"
};
string[] fileEntries = Directory.GetFiles(@"C:\Users\Dewagg\Desktop\test\");
List<String> badFiles = new List<string>();
foreach (string fileName in fileEntries)
if (!only_these_files.Contains(fileName))
{
badFiles.Add(fileName);
}
答案 0 :(得分:4)
如果要检查代码,则可以随时在其中放置断点并观察执行情况。您需要在桌面上创建文件,以便了解预期结果。
如果您想验证没有任何错误文件,那么您可以检查错误文件列表的大小。
所以你想要的东西是:
Dim arrNames(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim arrValues(,) As String = New String(AscW(ChrW(dic_Vars.Count)), 1) {}
Dim i As Integer = 0
For Each key As KeyValuePair(Of String, String) In dic_Vars
arrNames(i, 0) = key.Key
arrValues(i, 0) = key.Value
i += 1
Next
If Proceed Then
Dim r As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("B2").Resize(arrNames.GetLength(0))
Dim r2 As Microsoft.Office.Interop.Excel.Range = xlWorkSheet.Range("C2").Resize(arrValues.GetLength(0))
r.Value2 = arrNames
r2.Value2 = arrValues
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End If
答案 1 :(得分:1)
这不完全是火箭科学:这样的事情对你有用:
HashSet<string> allowedFiles = new HashSet<string>( StringComparer.OrdinalIgnoreCase )
{
"file1.exe" ,
"file2.dll" ,
};
DirectoryInfo directory = new DirectoryInfo( @"c:\foo\bar" ) ;
bool containsNonAllowedFiles = directory
.EnumerateFiles( @"C\foo\bar" )
.Any( fi => !allowedFiles.Contains( fi.Name ) )
;
bool containsAllAllowedFiles = allowedFiles
.All( fn => directory.EnumerateFiles( fn ).Any() )
;
答案 2 :(得分:0)
尝试这个,因为你只需要检查两个文件,这是一个糟糕的编码约定,使用一个arraylist来做你正在做的事btw
try{
if (!File.Exists("TextFile1.txt"))
throw new FileNotFoundException();
}
catch(FileNotFoundException e)
{
// your message here.
}