CodeCatia
CodeCatia

Reputation: 127

DeleteFile() or File.Delete() or Kill()

I'm migrating some code from VBA to VB.net and i have stuck at one simple thing. How to delete file. Can some one explain what is difference between these three methods:

My.Computer.FileSystem.DeleteFile("D:\file.xls")

System.IO.File.Delete("D:\file.xls")

FileSystem.Kill("D:\file.xls")

I only need to delete all specific file types in the folder. With VBA I used FileSystem.Kill, and with this method I don't have to loop through all files, I can delete all the specific files using

 FileSystem.Kill("D:\*.xls*")

What is best practice in VB.net to delete specific files?

Upvotes: 1

Views: 6592

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415630

The first option and the second are effectively the same, as the My namespace just aliases types elsewhere (in this case, System.IO.File).

With that in mind, I prefer the second option, as it is more portable across environments (I've been several places that mix the use of VB.Net with other .Net languages like C# or F#, which don't have the My namespace).

I avoid use of the vb6-era APIs, but really there's nothing wrong with it for the moment. Still, given the same mixed-environment issues as before, I would tend to write code like this:

Dim dir As New DirectoryInfo("D:\");
For Each file As FileInfo In dir.EnumerateFiles("*.xls")
    file.Delete()
Next

Or this:

For Each fileName As String In Directory.EnumerateFiles("D:\", "*.xls")
    File.Delete(fileName)
Next

Upvotes: 2

Related Questions