Search

Thursday, March 20, 2008

how to delete files in folder and subfolders in C#

Sample code in C# .Net to delete files in folders and subfolders

//to call the below method
EmptyFolder(new DirectoryInfo(@"C:\your Path"))


using System.IO; // dont forget to use this header

//Method to delete all files in the folder and subfolders

private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{

File.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}

let us know if you have any problem

8 comments:

Anonymous said...

thanks alot

Unknown said...
This comment has been removed by the author.
Unknown said...

this is not working, you got a little typo in here:

File.Delete(); should be:

file.Delete();

to make it work correctly

Yair Nevet said...

and if I'm lso want to selete the subfolders?

Anonymous said...

It does a recursive call when calling EmptyFolder(subfolder), which will delete the subfolders.

Florin Druga said...

just what i was looking for, thanks!

Florin Druga said...

at first i was a litlle confused, because in my app the path of the folder was taken from a database table, so it was passed inside the procedure, giving the object only the id of the row where it was.

Looking closely i realized that it was not possible, so i maked the second procedure to get the path, and from there i called the first one.

I also have an if clause, deleting only the files older than a number of days, also taken from the database.


public void ClearFiles_OlderThan(DirectoryInfo directoryInfo, int id)
{
DataBase db = new DataBase();
DataTable dt = new DataTable();

string SQLcommandE = "SELECT timeEX_zile FROM tbl_DeleteFilesOlderThan WHERE ID_delP=";
dt = db.LoadTable(SQLcommandE + id);

object OlderThan = new object();
OlderThan = dt.Rows[0][0];

string o = OlderThan.ToString();
double days = Convert.ToDouble(o);

foreach (FileInfo file in directoryInfo.GetFiles())
{
System.DateTime today = System.DateTime.Now;
System.DateTime older = today.AddDays(-days);
if (file.CreationTime < older)
{
file.Delete();
}
else
{

}

}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
ClearFiles_OlderThan(subfolder, id);
}
}
public void ClearFiles_OlderThanID(int id)
{
DataBase db = new DataBase();
DataTable dt = new DataTable();
object FolderPath = new object();

string SQLcommandP = "SELECT delP_path FROM tbl_FolderToDeletePaths WHERE ID_delP=";
dt = db.LoadTable(SQLcommandP + id);

FolderPath = dt.Rows[0][0];
string path = (string)FolderPath;

DirectoryInfo info = new DirectoryInfo(path);
ClearFiles_OlderThan(new DirectoryInfo (path), id);
}

Anonymous said...

is this code can be apply to windows mobile device?

Post a Comment

Other Interesting Articles



Related Article Widget by Yogith

Search Powered by Google