I am currently working on tool that will delete stuff in my temp folder and I've made it so it deletes Files such as text files and folders but how do I make it so it deletes RAR files and JPG's etc? is it possible?
This is my current code
private void Clear_Click(object sender, EventArgs e)
{
string tempPath = Path.GetTempPath();
DirectoryInfo di = new DirectoryInfo(tempPath);
foreach (DirectoryInfo dir in di.GetDirectories())
{
try
{
dir.Delete(true);
}
catch (Exception)
{
// Log error.
continue;
}
}
foreach (FileInfo file in di.GetFiles())
{
try
{
file.Delete();
}
catch (Exception)
{
// Log error.
continue;
}
}
}
The DirectoryInfo.GetFiles()
can accept a search pattern parameter.
foreach (FileInfo file in di.GetFiles("*.jpg"))
{
file.Delete();
}
This would delete any file with .jpg
extension. You can do the same for .rar
Optionally I would suggest creating a method to do this.
public void DeleteFiles(DirectoryInfo di, string searchPattern)
{
foreach (FileInfo file in di.GetFiles(searchPattern))
{
file.Delete();
}
}
Once this is created then you can just it like this.
DeleteFiles(di, "*.jpg");
If you have a list of all the extensions that you need you can loop through them.
string[] extentionList = new[] {"*.jpg", "*.rar", "*.bmp", "*.gif"};
foreach (string extension in extentionList)
{
DeleteFiles(di, extension);
}
If you will be using this in a variety of places, converting it to a DirectoryInfo
extension method would be the best choice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.