Check if remote files exist using C#

public void CheckFile()
    {
        // The two different files as strings.
        string urlfile1 = "http://remotehost.com/file1.zip";
        string urlfile2 = "http://remotehost.com/file2.zip";
 
        try
        {
            // Check to see if urlfile1 exists
            HttpWebRequest myrequest = (HttpWebRequest)WebRequest.Create(urlfile1);
            myrequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)myrequest.GetResponse();
            Console.WriteLine(urlfile1 + "Found");
        }
        catch (Exception ex)
        {
            // Check to see if urlfile2 exists
            HttpWebRequest myrequest2 = (HttpWebRequest)WebRequest.Create(urlfile2);
            myrequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;
            HttpWebResponse response;
            try
            {
                response = myrequest2.GetResponse() as HttpWebResponse;
            }
            catch (WebException exc)
            {
                response = exc.Response as HttpWebResponse;
            }
 
            // Check if response returns 404
            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                Console.WriteLine(urlfile1 + "Not Found");
            }
            else
            { 
                 if(response.StatusCode == HttpStatusCode.Ok)
                 {
                     Console.WriteLine(urlfile1 + "Found");
                 }
             }
        }

Enjoyed this post? Share it!

 

Leave a comment

Your email address will not be published.