Search code examples
c#fileinfo

FileInfo remove file from list


I have a method in C# which gets files in a directory this way:

FileInfo[] fileInfo = new DirectoryInfo(mypath).GetFiles();

Some of the files in the directory are not the ones we need to process (the only way to know is by its content, not the file extension) so we would like to remove them from the FileInfo list (not from disk).

I was searching for a simple way to exclude a file in the FileInfo array but there seems not to be a way.

Here's the whole code which checks the files we only need in the directory the user selects:

int number_of_files = fileInfo.Length;
for (int i = 0; i < number_of_files ; ++i)
{
    string file= fileInfo[i].FullName;
    BinaryReader br = new BinaryReader(new FileStream(file, FileMode.Open, FileAccess.Read), Encoding.ASCII);
    byte[] preamble = new byte[132];
    br.Read(preamble, 0, 132);
    if (preamble[128] != 'D' || preamble[129] != 'I' || preamble[130] != 'C' || preamble[131] != 'M')
    {
        if (preamble[0] + preamble[1] != 0008)  
        {
            return; //Rather than return, remove the file in question from the list....
        }
    }
    br.Dispose();
}

Any ideas how can I do this?


Solution

  • Instead of removing the file from the FileInfo[] array, consider just creating a separate list that collects all files that you do want to keep:

    FileInfo[] files = new DirectoryInfo(mypath).GetFiles();
    List<FileInfo> filteredFiles = new List<FileInfo>();
    foreach (FileInfo file in fileInfos)
    {
        string file= fileInfo[i].FullName;
        using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
        using (var br = new BinaryReader(stream, Encoding.ASCII))
        {
            byte[] preamble = new byte[132];
            br.Read(preamble, 0, 132);
            if (preamble[128] != 'D' || preamble[129] != 'I' || preamble[130] != 'C' || preamble[131] != 'M')
            {
                if (preamble[0] + preamble[1] != 0008)
                {
                    // skip this file
                    continue;
                }
    
                // keep the file
                filteredFiles.Add(file);
    
                // do something else with the file
            }
        }
    }
    

    You should think about whether reading the files just to filter them is really worth the effor though. If you later end up processing the filtered files too, you should really consider doing that at the same time, so you don’t have to open the file twice (once to figure out that you want to keep it, and once to actually process it). That way, you could also get rid of the filteredFiles list since you can just skip the files you are not interested in and process the other ones.