C# 尝试删除文件夹中的所有文件(c中的2个选定文件除外)#

C# 尝试删除文件夹中的所有文件(c中的2个选定文件除外)#,c#,delete-file,C#,Delete File,我只是想写一个简单的程序,清除我的“路径”文件夹exept为2.exe文件预选。问题是我只成功删除了第一个文件(file1.exe)。 我做错了什么?如果我使用逻辑运算符,请原谅,但在这一刻,我的头就要爆炸了 string[] filePaths = Directory.GetFiles(Path); foreach (string filePath in filePaths) { var name = new FileInfo(filePath).Name; name = na

我只是想写一个简单的程序,清除我的“路径”文件夹exept为2.exe文件预选。问题是我只成功删除了第一个文件(file1.exe)。 我做错了什么?如果我使用逻辑运算符,请原谅,但在这一刻,我的头就要爆炸了

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

根据您的情况使用
&&
而不是
|

if (name != "file1.exe" && name != "file2.exe")
还可以使用LINQ表达式筛选出文件,如:

var filePaths = Directory.GetFiles(Path)
                        .Where(r=> !r.Equals("file1.exe", StringComparison.InvariantCultureIgnoreCase)
                                   && !r.Equals("file2.exe", StringComparison.InvariantCultureIgnoreCase));
然后你可以做:

foreach (string filePath in filePaths)
{
    File.Delete(filePath);
}

您基本上是说,如果名称不等于“file1.exe”或name!=“file2.exe”然后删除一个文件路径,问题是您使用的是OR逻辑运算符,因此它只删除一个。尝试使用&。

它会一直删除我的file2.exe,但它不应该这样做。确保文件的名称与字符串中的名称相同,以便进行比较。进行字符串比较时,请确保忽略大小写。此外。。。将我作为另一个投票人加入,使用&&而不是| |是的,谢谢你,这是一个大写字母在起作用!你的问题是“谜语”背后的前提。