dames dames - 5 months ago 48
C# Question

Delete Files of multiple File types in c#

I have the following solution to delete a single file type with only one extension; however I am trying to find a way to incorporate multiple file extensions, for example:

.wma, .mp3, .wav

DirectoryInfo di = new DirectoryInfo(@"C:\");
FileInfo[] files = di.GetFiles("*.mpeg")
.Where(p => p.Extension == ".mpeg").ToArray();
foreach (FileInfo file in files)
file.Attributes = FileAttributes.Normal;
catch { }


Well that's just a matter of changing your condition to be "where the extension is any one of a set" and removing the pattern from the GetFiles call. Also note that you don't need to call ToArray() - just iterate over the results:

var extensions = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase)
    { ".wma", ".mp3", ".wav" };

var files = new DirectoryInfo(@"c:\").GetFiles()
                                     .Where(p => extensions.Contains(p.Extension));
foreach (var file in files)
    // try/catch if you really need, but I'd recommend catching a more
    // specific exception
    file.Attributes = FileAttributes.Normal;