开发者

Delete files whose filename starts with a certain number

I'm trying to delete all files in a folder which start with a specific user id so if the user id = 00000 then I want to delete file 00000-1.xml & 00000-2.xml & 00000-3.xml and so on.

I have this code so far:

    Dim path as String = Server.MapPath("../myfolder/xml/00000" & something?? & ".xml")

    If path <> "" Then
        Dim fileInfo As FileInfo = Nothing
        Try
            fileInfo = New FileInfo(path)
            If fileInfo.Exists Then
                File.Delete(path)
            End If
        Catch
        End Try

    End If

Obviously I have just added the 开发者_JS百科something?? in as i have no idea what to put there?

Can anyone shed any light on this?


Consider using Directory.GetFiles instead.

Dim path as String = Server.MapPath("../myfolder/xml")
If path <> "" Then
    Dim fileName As String
    For Each fileName in Directory.GetFiles (path, "00000-*.xml")
            File.Delete(fileName)
    Next

End If


You can also just enumerate through any files, if they exist like this (will need to convert to VB syntax):

foreach (string DeleteFileName in Directory.EnumerateFiles(Server.MapPath(@"../MyFolder/xml"), "00000*.xml"))
{
    File.Delete(Path.Combine(Server.MapPath(@"../MyFolder/xml"), DeleteFileName));
}

Note, I don't recall offhand whether EnumberateFiles gives just the file name or the fullpath. if fullpath, you can drop the Path.Combine().


Using LINQ:

Directory.EnumerateFiles(Server.MapPath(@"../myfolder/xml", "0000*.abc")).ToList().ForEach(File.Delete);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜