我的代码从图像文件中检索到"Date Taken"属性,并将其存储为字符串。然后,它将该字符串传回Main Sub,并尝试将其与其他日期(系统时间)进行比较。我收到一个错误,说我无法将字符串日期转换为日期。(从字符串转换)8/5/2014"输入"日期"无效。)
在下面的代码中,有两行注释掉了。当执行这些行时,程序将按预期工作(字符串将转换为日期)。注释行中的日期与程序获取日期完全匹配(视觉上);尽管如果我从观察窗口复制并粘贴,它也会失败。
Imports System.IO
Imports System.Globalization
Module Module1
Sub Main()
Dim topLevelFolder As New DirectoryInfo("C:UsersamitchellDesktoptest1")
Dim cutoffDate As DateTime = DateTime.Now.AddDays(-30)
Dim Dtaken As String
Dim PassFile
Dim Dtaken2
Using outputFile As New StreamWriter("output_file.txt")
For Each currentFile In topLevelFolder.EnumerateFiles("*.*", SearchOption.AllDirectories)
PassFile = currentFile.FullName
Dtaken = GetProperty(PassFile, 12)
'Dtaken = "8/5/2014"
'Dtaken2 = IsDate(Dtaken)
If Dtaken > cutoffDate Then
outputFile.WriteLine(currentFile.FullName)
End If
Next
End Using
End Sub
Function GetProperty(strFile, n)
Dim objShell As Object
Dim objFolder
Dim objFolderItem
Dim i
Dim strPath
Dim strName
Dim intPos
On Error GoTo ErrHandler
intPos = InStrRev(strFile, "")
strPath = Left(strFile, intPos)
strName = Mid(strFile, intPos + 1)
objShell = CreateObject("shell.application")
objFolder = objShell.NameSpace(CObj(strPath))
objFolderItem = objFolder.ParseName(strName)
If Not objFolderItem Is Nothing Then
GetProperty = objFolder.GetDetailsOf(objFolderItem, n)
GetProperty = Left(GetProperty, InStrRev(GetProperty, " ") - 1)
GetProperty = Left(GetProperty, InStrRev(GetProperty, " ") - 1)
End If
ExitHandler:
objFolderItem = Nothing
objFolder = Nothing
objShell = Nothing
Exit Function
ErrHandler:
MsgBox(Err.Description, vbExclamation)
Resume ExitHandler
End Function
End Module
那个代码让我很难过。它遵循了许多对vb6/vbscript时代有意义的约定,但对.Net代码来说就不那么好了。结果是,大部分代码都在复制.Net Framework为您处理的工作(并且做得更好)。我会为你拥抱Using
区块而称赞你,所以还有希望。
此代码更好地利用了.Net Framework。它从不将任何日期值呈现为字符串,从而完全避开了您的问题。
Imports System.IO
Module Module1
Sub Main()
Dim topLevelFolder As New DirectoryInfo("C:UsersamitchellDesktoptest1")
Dim cutoffDate As DateTime = DateTime.Now.AddDays(-30).Date
Using outputFile As New StreamWriter("output_file.txt")
Dim files = topLevelFolder.EnumerateFileSystemInfos("*.*", SearchOption.AllDirectories).
Where( Function(f) f.CreationTime > cutoffDate )
For Each file in files
outputFile.WriteLine(file.FullName)
Next file
End Using
End Sub
End Module
您在其中一个注释中提供的日期字符串在每个日期部分(?8/?5/?2014)
的开头包含三个U+0000
字符,其中?
表示U+0000
的出现
为了让约会顺利进行,你需要去掉这些。
我不知道为什么一个String
能在另一个不能的地方工作。您通常必须将String
转换为DateTime
才能进行比较。尝试以下操作:
Dim dt As DateTime = DateTime.Parse(Dtaken)
然后
If dt > cutoffDate Then
编辑:我投票认为乔尔的答案是最有可能的解决方案,但我会把它保留在这里,以便附上评论。