Pergunta

I want to develop a C# application that allows users to give an extension (example: *.mp3) And then the application will remove all files that contains this extension from the hard disk.

Foi útil?

Solução

This is just an example to delete files with .msi extension in C drive,

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

To get all extensions,

public List<FileInfo> GetFiles(string path, params string[] extensions)
{
    List<FileInfo> list = new List<FileInfo>();
    foreach (string ext in extensions)
        list.AddRange(new DirectoryInfo(path).GetFiles("*" + ext).Where(p =>
              p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase))
              .ToArray());
    return list;
}

Outras dicas

Put needed path in below code and use a foreach and File.Delete.

Use

var files = System.IO.Directory.GetFiles(path, "*.txt");

You can use Directory.EnumerateFiles(string path, string searchPattern, SearchOption searchOption) :

var files = Directory.EnumerateFiles(directoryPath, "*.mp3", SearchOption.AllDirectories);
foreach (var item in files)
{
   try
   {
       File.Delete(item);
   }
   catch (Exception)
   { //log exception}
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top