ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

DeleteFiles

Delete all files found on the specified folder with a given file extension.

Source

using System.IO;

public static class MyExtensions
{
	public static void DeleteFiles(this string folderPath, string ext)
	{
		string mask = "*." + ext;

		try
		{
			string[] fileList = Directory.GetFiles(folderPath, mask);

			foreach (string file in fileList)
			{
				FileInfo fileInfo = new FileInfo(file);
				fileInfo.Delete();
			}
		}
		catch (Exception ex)
		{
			//Console.WriteLine("Error Deleting file. Reason: {0}", ex.Message);
		}
	}
}

Example

string path = @"C:\Temp\test\Sharp";
path.DeleteFiles("cs"); // Deletes all files with a CS extension

Author: Earljon Hidalgo

Submitted on: 26 mrt. 2008

Language: C#

Type: System.String

Views: 5128