Pages

Monday, January 31, 2011

Get FTP Server Time

http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/56137d13-9bf5-4f35-9358-88b5009709fa

Private Function GetFtpServerDateTime(ByVal ftpServer As String, ByVal username As String, _
                                      ByVal password As String) As Date
        Dim ftpFile As String
        If Not ftpServer.EndsWith("/") Then
            ftpServer &= "/"
        End If
        ftpFile = String.Concat(ftpServer, "tmptimecheck.zero")
        Dim dateStr As String = String.Empty
        Dim request As System.Net.FtpWebRequest = System.Net.FtpWebRequest.Create(ftpFile)
        Dim creds As New System.Net.NetworkCredential(username, password)
        request.Credentials = creds
        request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
        Dim response As System.Net.FtpWebResponse = request.GetResponse
        If response.StatusCode = Net.FtpStatusCode.ClosingData Then
            response.Close()
            request = System.Net.FtpWebRequest.Create(ftpFile)
            request.Credentials = creds
            request.Method = System.Net.WebRequestMethods.Ftp.GetDateTimestamp
            response = request.GetResponse
            If response.StatusCode = Net.FtpStatusCode.FileStatus Then
                dateStr = response.StatusDescription
                response.Close()
                request = System.Net.FtpWebRequest.Create(ftpFile)
                request.Credentials = creds
                request.Method = System.Net.WebRequestMethods.Ftp.DeleteFile
                response = request.GetResponse
            End If
            response.Close()
        End If
        response.Close()
        If dateStr.Length = 20 Then
            dateStr = dateStr.Substring(4)
            Dim year As Integer = CInt(dateStr.Substring(0, 4))
            Dim month As Integer = CInt(dateStr.Substring(4, 2))
            Dim day As Integer = CInt(dateStr.Substring(6, 2))
            Dim hour As Integer = CInt(dateStr.Substring(8, 2))
            Dim minute As Integer = CInt(dateStr.Substring(10, 2))
            Dim second As Integer = CInt(dateStr.Substring(12, 2))
            Return New Date(year, month, day, hour, minute, second)
        Else
            Throw New Exception("Error while attempting to infer date from server")
        End If
End Function

No comments:

Post a Comment