Search code examples
vb.netdatevisual-studio-2012date-conversion

Conversion from string "‎8/‎5/‎2014" to type 'Date' is not valid


My code has retrieved the "Date Taken" property from an image file and stored it as a string. It then passes that string back to the Main Sub where it tries to compare it to an other date (system time). I receive an error saying i can't convert my string date to a Date. (Conversion from string "‎8/‎5/‎2014" to type 'Date' is not valid.)

In the code below there are two commented-out lines. When these lines are executed the program works as expected (the string is converted to a date). The date in the commented-out line matches (visually) the programmatic acquired date exactly; although if i copy and paste from the watch window it will also fail.

    Imports System.IO
    Imports System.Globalization

Module Module1

    Sub Main()

        Dim topLevelFolder As New DirectoryInfo("C:\Users\amitchell\Desktop\test1\")
        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

Solution

  • The date string you provided in one of the comments contains three U+0000 characters at the start of each date portion (?8/?5/?2014) where the ? denote occurences of U+0000

    You'll need to strip these out in order to make the date work.