Delete files with a particular extension (C#)

You can delete files using a simple batch file. That is,

cd C:\test
del *.txt

This code deletes all text files in C:\test (but not recursively).

Tips: "*" means an arbitrary name.

C# Code

var files = Directory.GetFiles( "C:\test", "*.txt" );
foreach ( var file in files )
{
    File.Delete( file );
}

Of course, you can use a Parallel.ForEach loop. Deleting files parallelly must be processed after listing files.

var files = Directory.GetFiles( "C:\test", "*.txt" );
Parallel.ForEach( files, file =>
    {
        File.Delete( file );
    }
);

Using File Class, "*" means an arbitrary name.

おしらせ

受験生、大学生、数学の好きな大人の方に向けて、センター数ⅡBの過去問を解く勉強会を開催します。

広告