我有以下代码
Public Function ListDirLatest(ByVal Dir As String, ByVal Amount As Integer) As DataTable
Dim dt As DataTable = ListDir(Dir)
If (dt Is Nothing) Then
Return Nothing
Else
Return dt ' This is where i would like to implement the latest x-files logic
End If
End Function
Private Function ListDir(ByVal Dir As String) As DataTable
If Directory.Exists(Dir) Then
Dim dt As DataTable = GetDT()
Dim dirinfo As New DirectoryInfo(Dir)
For Each fsi As FileSystemInfo In dirinfo.GetFileSystemInfos(".txt")
Dim dr As DataRow = dt.NewRow()
dr("FileName") = fsi.Name()
dr("FileDate") = fsi.CreationTime()
Next
Return dt
Else
Return Nothing
End If
End Function
Private Function GetDT() As DataTable
'Create DataTable to hold results
Dim dt As New DataTable("DirList")
Dim st As System.Type = System.Type.GetType("System.String")
dt.Columns.Add("FileName", st)
dt.Columns.Add("FileDate", st)
Return dt
End Function
目前ListDirLatest
函数将返回目录中的所有文件。
如何更改代码,使其仅返回Amount
参数指定的最新“x”文件。
澄清我想在目录中返回最新的'x'文件。
答案 0 :(得分:2)
您可以使用Linq和System.Data.DataSetExtensions的一些引用来解决您的问题 (http://msdn.microsoft.com/en-us/library/system.data.datatableextensions(v=vs.100).aspx)
Public Function ListDirLatest(ByVal Dir As String, ByVal Amount As Integer) As DataTable
Dim dt As DataTable = ListDir(Dir)
If (dt Is Nothing) Then
Return Nothing
Else
Dim r = from myRow in dt.AsEnumerable()
Order By("FileDate DESC")
Take(Amount)
dt = r.CopyToDataTable()
return dt
End If
End Function
此外,ListDir函数有几个错误
为GetFileSystemInfos使用正确的模式
Function ListDir(ByVal Dir As String) As DataTable
If Directory.Exists(Dir) Then
Dim dt As DataTable = GetDT()
Dim dirinfo As New DirectoryInfo(Dir)
For Each fsi As FileSystemInfo In dirinfo.GetFileSystemInfos("*.txt")
Dim dr As DataRow = dt.NewRow()
dr("FileName") = fsi.Name()
dr("FileDate") = fsi.CreationTime()
dt.Rows.Add(dr)
Next
Return dt
Else
Return Nothing
End If
End Function
答案 1 :(得分:0)
如果您指的是Amount要返回的文件数,那么您需要执行以下操作:
首先更改ListDir函数的标题以接受参数以允许计算要返回的文件数,并从第一个函数传递该参数,
Public Function ListDirLatest(ByVal Dir As String, ByVal Amount As Integer) As DataTable
Dim dt As DataTable = ListDir(Dir, Amount)
If (dt Is Nothing) Then
Return Nothing
Else
Return dt ' This is where i would like to implement the latest x-files logic
End If
End Function
Private Function ListDir(ByVal Dir As String, ByVal Amount As Integer) As DataTable
If Directory.Exists(Dir) Then
Dim dt As DataTable = GetDT()
Dim dirinfo As New DirectoryInfo(Dir)
Dim cnt as Integer = 0
For Each fsi As FileSystemInfo In dirinfo.GetFileSystemInfos(".txt")
Dim dr As DataRow = dt.NewRow()
dr("FileName") = fsi.Name()
dr("FileDate") = fsi.CreationTime()
cnt += 1
if cnt >= Amount Then Exit For
Next
Return dt
Else
Return Nothing
End If
End Function