Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Delete All Files in Folder 3

Status
Not open for further replies.

jasonp45

Programmer
Aug 23, 2001
212
US
I want to write a sub that will accept a folder parameter (string, as in: "C:\Temp") and then delete all the files in that folder. Can anyone tell me what a simple way to accomplish this is? I don't see an obvious method for the Directory object; I assume I could get the file list for the Directory and then explicitly delete each file, but is there a single-command method?

Thanks!
 
The following will delete all files in a folder (in this case, C:\Test).

Use with caution!!! :)
Code:
Dim d As System.IO.Directory, f As System.IO.File, i As Int32

Dim s() As String = d.GetFiles("C:\Test")

For i = 0 To s.GetUpperBound(0)

	f.Delete("C:\Test\" & s(i))

Next
 
The Directory.GetFiles() function will return the full path to all the files in a given directory. Therefore, the drive and directory literal in the following statement "f.Delete("C:\Test\" & s(i))", added to the element in the string array, will produce a string that looks like the following "C:\Test\C:\Test\MyFile.txt" and an exception will be thrown. If you remove the "C:\Test\" literal from the File.Delete() function the code will work well.
 
Oops, well spotted stravis.

I guess I should test before posting... :-(
 
It happens to the best of us, by us I don't mean me, not meaning that I don't make mistakes, but that I don't belong in the grouping of "the best". I'll reserve that title for people such as yourself, not me. [3eyes]
 
Thanks guys. I also got the following suggestion from the Microsoft VB.NET newsgroup:

(1)
Dim di as New System.IO.DirectoryInfo("ZZ:\")

'// Delete the entire ZZ:\ volume, including all files & subdirs
di.Delete( True )

(2)
Dim s As String
For Each s In System.IO.Directory.GetFiles("C:\WINDOWS\TEMP")
System.IO.File.Delete(s)
Next s
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top