Andrew
Andrew

Reputation: 552

How to filter File.Delete function to certain file extensions?

I use the following function in c# to delete all contents in a folder; however, I am wondering if I can add onto this function to only delete files with the file extension ".dll".

Array.ForEach(Directory.GetFiles(DIRname), File.Delete);

Thanks.

Upvotes: 0

Views: 152

Answers (2)

loopedcode
loopedcode

Reputation: 4893

File.Delete doesn't support any wildcard.

You can use one of the two options below (uses "*.dll" wildcard, you can change it as needed).

Get all files and use Parallel.ForEach to delete them in parallel, much faster than normal loop.

    var files = Directory.GetFiles(@"c:\mypath", "*.dll");
    Parallel.ForEach(files, (f)=> File.Delete(f));

Or, use the windows command shell with DEL command:

    Process process = new Process()
    {
        StartInfo = new ProcessStartInfo()
        {
            UseShellExecute = false,
            RedirectStandardOutput = true,
            CreateNoWindow = true,
            RedirectStandardInput = true,
            RedirectStandardError = true,
            FileName = "cmd.exe",
            Arguments = @"/C del c:\mypath\*.dll",

        }
    };
    process.Start();
    process.WaitForExit();

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You can use overloaded method Directory.GetFiles(string,string) topass SearchPattern as *.dll to get all the files with the extension of .dll

Directory.GetFiles()

Returns the names of files (including their paths) that match the specified search pattern in the specified directory.

Try This:

Directory.GetFiles(DIRname,"*.dll")

Upvotes: 3

Related Questions