获取文件夹中的文件

时间:2014-05-23 16:00:40

标签: .net vb.net

我想查看/显示我正在查看的文件夹(/上传)中的所有文件,然后查看' / uploads'中的所有子文件夹。

我的问题是我可以根据我的代码轻松完成这项工作。 (它读取文件夹中的文件并重命名)

 If Not IsPostBack Then
            'Dim pathIn As String
            Dim pathOut As String
            Dim vDate As String = DateTime.Now.ToString("yyyy-MM-dd")

            Dim filePaths() As String = Directory.GetFiles(Server.MapPath("~/Uploads/"))
            Dim files As List(Of ListItem) = New List(Of ListItem)
            For Each filePath As String In filePaths
                files.Add(New ListItem(Path.GetFileName(filePath), filePath))

                ' pathIn = filePath
                'RENAMES FILES HERE
                pathOut = "C:\sites\Examples\FilesInFolderList\Uploads\" & vDate & "_" & Replace(filePath, Server.MapPath("~/Uploads/"), "")

                '' Move the file.
                File.Move(filePath, pathOut)
                Console.WriteLine("{0} moved to {1}", filePath, pathOut)


            Next
            GridView1.DataSource = files
            GridView1.DataBind()
        End If

1 个答案:

答案 0 :(得分:2)

使用DirectoryInfo.GetFiles,您可以搜索子目录。

    If Not IsPostBack Then
        Dim pathOut As String
        Dim vDate As String = DateTime.Now.ToString("yyyy-MM-dd")
        Dim files As New List(Of ListItem)
        For Each File As FileInfo In New DirectoryInfo(Server.MapPath("~/Uploads/")).GetFiles("*.*", SearchOption.AllDirectories)
            files.Add(New ListItem(File.Name, File.FullName))
            pathOut = "C:\sites\Examples\FilesInFolderList\Uploads\" & vDate & "_" & File.Name
            Console.WriteLine("{0} moving to {1}", File.FullName, pathOut)
            File.MoveTo(pathOut)
        Next
        GridView1.DataSource = files
        GridView1.DataBind()
    End If