Answered by:
Delete all the files from folder

Question
-
Hi,
I have a folder called C:\MyFolder. This folder has pdf and excel files. I just want to delete all files from folder. I see lot of forums showing code to loop thru all files in a folder and delete each. In other examples, delete code deletes entire folder that mean MyFolder also gets deleted. Need to recreate everytime. What I am looking is something like
directory.deleteAllFiles
syntax which deletes all files, but keeps the folder empty.
We are using asp.net c#. I need this to work both in 2.0 and 4.0
Please let me know if there are any links.
Thanks,
Spunny.
Thursday, February 20, 2014 3:57 AM
Answers
-
Spunny : Back up your folders and try this below which deletes main folder and sub folders..
new DirectoryInfo(@"C:\temp\").GetFiles("*",SearchOption.AllDirectories).ToList().ForEach(x => File.Delete(x.FullName));
- Marked as answer by Caillen Thursday, February 27, 2014 8:05 AM
Thursday, February 20, 2014 3:37 PM
All replies
-
HI
Have you tried this
IO.Directory.Delete("folderPath",true)
ref :http://msdn.microsoft.com/en-us/library/system.io.directory.delete(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx
Mark as ans if you find it useful
Shridhar J Joshi Thanks a lot
Thursday, February 20, 2014 4:08 AM -
Thank you Shridhar for quick response. As I said in my post it deletes directory, subdirectory and files. In my case, your code deletes 'MyFolder' also. I don't want that to happen. I want only files to be deleted and not main directory.Thursday, February 20, 2014 4:15 AM
-
Try this code
System.IO.DirectoryInfo dirinfo = new DirectoryInfo(@"C:\MyFolder");
foreach (FileInfo file in dirinfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in dirinfo.GetDirectories())
{
dir.Delete(true);
}
Ashish Pandey
- Edited by Ashish Pandey Thursday, February 20, 2014 4:29 AM
- Proposed as answer by Shridhar J Joshi Thursday, February 20, 2014 4:31 AM
Thursday, February 20, 2014 4:27 AM -
Try this
For Each s As String In IO.Directory.GetFiles("Your folder name")
IO.File.Delete(s)
Next
For Each s As String In IO.Directory.GetDirectories("Your folder name")
IO.Directory.Delete(s, True)
NextMark as ans if you find it useful
Shridhar J Joshi Thanks a lot
Thursday, February 20, 2014 4:32 AM -
Thank you Shridhar and Ashish. I requested to know if there is any single line of code to delete all files without deleting directory with out looping through each file.
Spunny.
Thursday, February 20, 2014 3:25 PM -
Spunny : Back up your folders and try this below which deletes main folder and sub folders..
new DirectoryInfo(@"C:\temp\").GetFiles("*",SearchOption.AllDirectories).ToList().ForEach(x => File.Delete(x.FullName));
- Marked as answer by Caillen Thursday, February 27, 2014 8:05 AM
Thursday, February 20, 2014 3:37 PM