Solved

Check if file exists on HTTP server VB.NET

Posted on 2010-09-01
4
2,355 Views
Last Modified: 2012-08-14
What is the easiest way to find out if a file exists on an HTTP server?
'----Obviously this does not work but it would have been good

'----if there is a simple way to do this



Dim curFile As String = "http://www.server.com/test.txt"

Console.WriteLine(If(File.Exists(curFile), "File exists.", "File does not exist."))

Open in new window

0
Comment
Question by:jes12345
  • 2
4 Comments
 
LVL 29

Expert Comment

by:Kumaraswamy R
ID: 33575703
0
 
LVL 29

Assisted Solution

by:Kumaraswamy R
Kumaraswamy R earned 75 total points
ID: 33575705
0
 
LVL 11

Accepted Solution

by:
azarc3 earned 350 total points
ID: 33575774
This needs to be tested as it's an adaptation of what I'm currently using myself... the only problem is that since you're going across the HTTP protocol you're not exactly "guaranteed" that you won't get false positives... however, 404s are usually consistent. That's what you're really concerned about, anyway.


Imports System.IO

Imports System.Net



Using oRequest As New System.Net.WebClient

    Try

        Using theCall As Stream = oRequest.OpenRead(http://www.server.com/test.txt")

            Using theReader As New StreamReader(theCall)

                Dim theResult As String = theReader.ReadToEnd()

                If theResult.Length > 0 Then Console.WriteLine("File exists.")

            End Using

        End Using

    Catch ex As Exception

        If ex.Message.ToLowerInvariant.Contains("the remote server returned an error: (404) not found.") _

                OrElse ex.Message.ToLowerInvariant.Contains("the remote name could not be resolved") _

            Then

            Console.WriteLine("File does not exist.")

        End If

    End Try

End Using

Open in new window

0
 
LVL 5

Assisted Solution

by:Leithauser
Leithauser earned 75 total points
ID: 33577816
This is code to get a list of files at an FTP location. It is written for VB 6, but shoudl work with minor adaptation in VB.Net. Substittue your own FTPAddress, FTPUserName,
FTPPassword, and FolderName.

Global FTPAddress As String, FTPUserName As String, FTPPassword As String, FileType As Long, FolderName As String
Global InternetDirectoryList() As String, NumInternetDirectoryList As Integer
Global OperationFailed As Integer
Private Const ERROR_NO_MORE_FILES = 18
Global Const vbBinaryCompare = 0
Private Type FILETIME
        dwLowDateTime As Long
        dwHighDateTime As Long
End Type

Private Type WIN32_FIND_DATA
        dwFileAttributes As Long
        ftCreationTime As FILETIME
        ftLastAccessTime As FILETIME
        ftLastWriteTime As FILETIME
        nFileSizeHigh As Long
        nFileSizeLow As Long
        dwReserved0 As Long
        dwReserved1 As Long
        cFileName As String * 260 ' MAX_PATH
        cAlternate As String * 14
End Type
Public Declare Function FtpSetCurrentDirectory Lib "wininet.dll" Alias "FtpSetCurrentDirectoryA" _
    (ByVal hFtpSession As Long, ByVal lpszDirectory As String) As Boolean
Private Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA" _
    (ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, _
    ByVal sProxyBypass As String, ByVal lFlags As Long) As Long
'The sAgent parameter is used to specify the application or entity calling the WinINet functions. For our purposes, we can put “MyFTP Control”.
'The lAccessType parameter specifies whether we connect directly to a host or whether we use a proxy server for the connection. If we pass the value 1, we’ll connect directly to the host. If we pass the value 3, we’ll connect via a proxy server. If we pass 0, we’ll connect based on the registry values ProxyEnable, ProxyServer, and ProxyOverride located under HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings.
'Rather than using the registry settings, we can use the sProxyName and sProxyBypass parameters to provide the proxy server (or servers) and the list of IP addresses or names that should not be routed to the proxy. The basic format for listing a proxy is “protocol=protocol://proxy_name:access_port”. For example, to specify port 21 on Proxy1 as the proxy server, use “ftp=ftp://Proxy1:21” as the sProxyName. To bypass any host that starts with “nov”, the sProxyBypass string would be “nov*”.
'Finally, lFlags is used to indicate various options affecting the behavior of the InternetOpen function. For our example, we’ll pass 0.
'So, to open an Internet session without using a proxy, our call would be like this:
'lngINet = InternetOpen(“MyFTP Control”, 1, vbNullString, vbNullString, 0)
'If the function call fails, lngINet will be 0. Otherwise, lngINet holds the value of the handle that we’ll need to pass to the InternetConnect function in the next step.
Private Declare Function InternetConnect Lib "wininet.dll" Alias "InternetConnectA" _
    (ByVal hInternetSession As Long, ByVal sServerName As String, _
    ByVal nServerPort As Integer, ByVal sUsername As String, _
    ByVal sPassword As String, ByVal lService As Long, _
    ByVal lFlags As Long, ByVal lContext As Long) As Long
'The first parameter, hInternetSession is the value of the handle returned by the InternetOpen call.
'sServerName is the IP address or host name of the FTP server we’re connecting to.
'nServerPort indicates which port to connect to. For our example, we’ll use the value 0, which indicates the default port (21).
'sUsername and sPassword are used to pass the user name and password, respectively.
'The lService parameter is used to indicate the type of service to access, i.e., HTTP, FTP, etc. We’ll always pass the value of 1, indicating the FTP service.
'If we pass the value x8000000 in the lFlags parameter, the connection will use passive FTP semantics. Otherwise, as in our example, we can pass 0 to use non-passive semantics.
'Finally, lContext is used to identify the application context when using callbacks. Since we’re not using callbacks for our example, we’ll pass 0.
'So here’s the call to connect to the host FTP.MICROSOFT.COM using the anonymous userid:
'lngINetConn = InternetConnect(lngINet, “ftp.microsoft.com”, 0, _
    “anonymous”, “wally@wallyworld.com”, 1, 0, 0)
'If the function call fails, lngINetConn will be 0. Otherwise, lngINetConn holds the value of the handle that we’ll need to pass to the FtpGetFile function in the next step.
Private Declare Function FtpGetFile Lib "wininet.dll" Alias "FtpGetFileA" _
    (ByVal hFtpSession As Long, ByVal lpszRemoteFile As String, _
    ByVal lpszNewFile As String, ByVal fFailIfExists As Boolean, _
    ByVal dwFlagsAndAttributes As Long, ByVal dwflags As Long, _
    ByVal dwContext As Long) As Boolean
'The first parameter, hFtpSession is the value of the handle returned by the InternetConnect call.
'lpszRemoteFile and lpszNewFile are the names of the file on the FTP server and the file to create on the local machine, respectively.
'The fFailIfExists flag is either 0 (replace local file) or –1 (fail if local file already exists).
'dwFlagsAndAttributes can be used to specify file attributes for the local file. For our example, we’ll overlook this and just pass 0.
'We use the dwFlags parameter to specify 1 for transferring the file in ASCII (Type A transfer method) or 2 for transferring the file in Binary (Type I transfer method). Since DIRMAP.TXT is an ASCII text file, we’ll pass the value of 1.
'Finally, lContext is used to identify the application context when using callbacks. Since we’re not using callbacks for our example, we’ll pass 0.
'So here’s the call to get the DIRMAP.TXT file and store it in C:\DIRMAP.TXT. In case the local file already exists, we’ll overwrite it.
'blnRC = FtpGetFile(lngINetConn, “dirmap.txt”, “c:\dirmap.txt”, 0, 0, 1, 0)
'If the function call is successful, blnRC will be True, otherwise, blnRC will be False.
Private Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As Long) As Integer
Private Declare Function FtpPutFile Lib "wininet.dll" Alias "FtpPutFileA" _
    (ByVal hFtpSession As Long, ByVal lpszLocalFile As String, _
    ByVal lpszRemoteFile As String, ByVal dwflags As Long, _
    ByVal dwContext As Long) As Boolean
'The first parameter, hFtpSession is the value of the handle returned by the InternetConnect call.
'lpszNewFile and lpszRemoteFile are the names of the file on the local machine and the file to create on the remote host, respectively.
'We use the dwFlags parameter to specify 1 for transferring the file in ASCII (Type A transfer method) or 2 for transferring the file in Binary (Type I transfer method). Since DIRMAP.TXT is an ASCII text file, we’ll pass the value of 1.
'Finally, lContext is used to identify the application context when using callbacks. Since we’re not using callbacks for our example, we’ll pass 0.
'So here’s the call to get the C:\DIRMAP.TXT file and store it as DIRMAP.TXT on an FTP server:
'blnRC = FtpPutFile(lngINetConn, “c:\dirmap.txt”, “dirmap.txt”, 1, 0)

Private Declare Function FtpDeleteFile Lib "wininet.dll" Alias "FtpDeleteFileA" _
    (ByVal hFtpSession As Long, ByVal lpszFileName As String) As Boolean
Private Declare Function FtpFindFirstFile Lib "wininet.dll" Alias "FtpFindFirstFileA" (ByVal hFtpSession As Long, ByVal lpszSearchFile As String, lpFindFileData As WIN32_FIND_DATA, ByVal dwflags As Long, ByVal dwContent As Long) As Long
Private Declare Function InternetFindNextFile Lib "wininet.dll" Alias "InternetFindNextFileA" _
    (ByVal hFind As Long, lpvFindData As WIN32_FIND_DATA) As Long
 

Sub GetFileList(DestinationFile As String)

Dim pData As WIN32_FIND_DATA
Dim lngHINet As Long, lngINetConn As Long
Dim intError As Integer
Dim strTemp As String
Dim blnRC As Boolean
Dim FullDestinationPath As String
Dim lngINet As Long
Dim sUsername As String
FTPAddress = "WebSite.com"
FTPUserName = "TheUserName"
FTPPassword = "Password"
FolderName = "FolderName"
FileType = 1

sUsername = FTPUserName
OperationFailed = 0
lngINet = InternetOpen("CRCFTP Control", 1, vbNullString, vbNullString, 0)
If lngINet = 0 Then
    lngINet = InternetOpen("CRCFTP Control", 0, vbNullString, vbNullString, 0)
End If
If lngINet = 0 Then
    OperationFailed = 1
    Exit Sub
End If
DoEvents
lngINetConn = InternetConnect(lngINet, FTPAddress, 0, sUsername, FTPPassword, 1, 0, 0)
If lngINetConn = 0 Then
    OperationFailed = 2
    InternetCloseHandle lngINet
    Exit Sub
End If
DoEvents
If Len(FolderName) Then
    FullDestinationPath = FolderName & "/" & DestinationFile
End If

'init the filename buffer
pData.cFileName = String(260, 0)
'get the first file in the directory...
lngHINet = FtpFindFirstFile(lngINetConn, FullDestinationPath, pData, 0, 0)
NumInternetDirectoryList = 0
'how'd we do?
If lngHINet = 0 Then
    'get the error from the findfirst call
    intError = Err.LastDllError
    'is the directory empty?
    If intError = ERROR_NO_MORE_FILES Then
    Else
        'whoa...a real error
        OperationFailed = 3
        GoTo CloseItDown
    End If
Else
    'we got some dir info...
    'get the name
    strTemp = Left(pData.cFileName, InStr(1, pData.cFileName, String(1, 0), vbBinaryCompare) - 1)
    '…store the file info someplace…
    NumInternetDirectoryList = NumInternetDirectoryList + 1
    ReDim Preserve InternetDirectoryList(NumInternetDirectoryList)
    InternetDirectoryList(NumInternetDirectoryList) = strTemp
    'now loop through the rest of the files...
    Do
        'init the filename buffer
        pData.cFileName = String(260, 0)
       
        'get the next item
        blnRC = InternetFindNextFile(lngHINet, pData)
        'how'd we do?
        If Not blnRC Then
            'get the error from the findnext call
            intError = Err.LastDllError
            'no more items
            If intError <> 18 Then
                'whoa...a real error
                '…error handler…
                OperationFailed = 4
                InternetCloseHandle lngHINet
                GoTo CloseItDown
                Exit Do
            Else
                'no more items...
                Exit Do
            End If
        Else
            'get the last item returned
            strTemp = Left(pData.cFileName, InStr(1, pData.cFileName, String(1, 0), vbBinaryCompare) - 1)
            'DirectFTPForm.List1.AddItem strTemp '…store the file info someplace…
            NumInternetDirectoryList = NumInternetDirectoryList + 1
            ReDim Preserve InternetDirectoryList(NumInternetDirectoryList)
            InternetDirectoryList(NumInternetDirectoryList) = strTemp
        End If
    Loop
    'close the handle for the dir listing
    InternetCloseHandle lngHINet
    'DirectFTPForm.lblStatus = "Finished listing."
End If
CloseItDown:
InternetCloseHandle lngINetConn
InternetCloseHandle lngINet
End Sub
 
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article describes some techniques which will make your VBA or Visual Basic Classic code easier to understand and maintain, whether by you, your replacement, or another Experts-Exchange expert.
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now