Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete file of certain extension?

Tags:

c#

.net

I have an application that should unzip and install some other application, i get new Zip file with installation image via network and then should unzip it and install. All file except the part that Zip file comes with different name each time because of version change and all my C:\ has a lot of .zip files with different versions. Msi file is not overwritten by Zip i'm using but i'm more than fine with just deleting it prior to unzipping.

I want to delete all .msi and .zip files on C:. How can i do that via C#?

thanks...

like image 777
eugeneK Avatar asked Nov 15 '11 07:11

eugeneK


People also ask

How do I delete a file with the same extension in Linux?

To remove files with a specific extension, we use the 'rm' (Remove) command, which is a basic command-line utility for removing system files, directories, symbolic links, device nodes, pipes, and sockets in Linux. Here, 'filename1', 'filename2', etc. are the names of the files including full path.

How do I delete a recursive file?

To remove a directory and all its contents, including any subdirectories and files, use the rm command with the recursive option, -r . Directories that are removed with the rmdir command cannot be recovered, nor can directories and their contents removed with the rm -r command.


1 Answers

You could try something like this:

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

Note that I first try to set attributes to "normal", because File.Delete() fails if file is read-only...
Note the use of GetFiles(): see this link for details.

EDITED:
If you need to get more than one extension you could use this:

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; } 

so you can change part of my answer to

List<FileInfo> files = GetFiles(@"C:\", ".msi", ".zip"); 
like image 117
Marco Avatar answered Sep 29 '22 19:09

Marco