Filter specific file to not delete

Asked

Viewed 72 times

3

How to make the code not delete a specific file I want between the .exe which I picked up. Example: I want it not to delete "test.exe", but still to continue erasing all the rest.

Follows the code:

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

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 can do with LINQ, I would, because it is more performatic in this case. Doing right despite having a little bit of overhead for the infrastructure of LINQ it makes only one loop. In Barbetta’s answer he makes 2 loops, one to get the files and one to filter. The Enumerate does not perform loop some.

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

I put in the Github for future reference.

  • i) Sometimes I wish I had the option of +5 for your answers; ii) Sometimes we were worried about making a code more readable (I say this in the sense of step by step) that we ended up going round and round and "spending" more than I should.

  • I just didn’t give you +1 pq the first one is considerably less efficient than the second one, and it can mislead someone

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

1

You can use a conditional within the foreach itself, so:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.