Filter specific file not to delete

3

How to make the code not delete a specific file I want among the .exe I get. Example: I want it not to delete "test.exe", but still keep erasing everything else.

Follow the code:

string[] arquivos = Directory.GetFiles(@"C:\temp\ae", "*.exe", SearchOption.TopDirectoryOnly);
foreach (string arquivo in arquivos)
{
    //nome = Path.GetFileName(arquivo);
    File.Delete(arquivo);
}
    
asked by anonymous 28.05.2018 / 20:23

3 answers

7
foreach (var arquivo in Directory.GetFiles(@"C:\temp\ae", "*.exe", SearchOption.TopDirectoryOnly) {
    if (Path.GetFileName(arquivo) != "teste.exe") File.Delete(arquivo);
}

If you prefer you can do with LINQ, I would, because it is more performative in this case. Doing right despite having a bit of overhead by the LINQ infrastructure it does just a loop . In Barbetta's answer he does 2 loops , one to get the files and another to filter. The Enumerate does not execute loop any.

foreach (var arquivo in Directory.EnumerateFiles(@"C:\temp\ae", "*.exe", SearchOption.TopDirectoryOnly).Where(f => Path.GetFileName(f) != "teste.exe") File.Delete(arquivo);
    
28.05.2018 / 20:29
1

You can use a conditional within the foreach itself, like this:

    string[] arquivos = Directory.GetFiles(@"C:\temp\ae", "*.exe", SearchOption.TopDirectoryOnly);
    foreach (string arquivo in arquivos)
    {
        var nome = Path.GetFileName(arquivo);
        if (nome != "teste.exe")
            File.Delete(arquivo);
    }
    
28.05.2018 / 20:29
1

Follow one more option using linq

string[] arquivos = Directory.GetFiles(@"C:\temp\ae", "*.exe", SearchOption.TopDirectoryOnly).Where(p => p != "teste.exe").ToArray();
foreach (string arquivo in arquivos)
    File.Delete(arquivo);
    
28.05.2018 / 20:38