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...
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.
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.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With