Ensure that a valid URL exist and download the data from a text file hosted on the server from C#

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 306
The below code will do so

using System;
using System.Net;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fileLocation = @"http://xyz.net/sample.txt";
var serverResponse = GetServerResponse(fileLocation);
Console.WriteLine("URL Validity : {0} \n Server Response : {1}", serverResponse.Item1, serverResponse.Item2);
Console.ReadKey();
}

private static Tuple<bool,string> GetServerResponse(string fileLocation)
{
bool isValidURL = true;
string data = string.Empty;
using (WebClient client = new WebClient())
{
try
{
data = client.DownloadString(fileLocation);
}catch(WebException weX){
isValidURL = !isValidURL;
data = weX.Message;
}
}
return Tuple.Create<bool, string>(isValidURL, data);
}
}
}


We are using the WebClient class for this purpose that resides under System.Net .The WebClient class Provides common methods for sending data to and receiving data from a resource identified by a URI.This program checks if a file Exists at a specified URI and if so, returns the file content.If the URL is correct and the file exists at the proper URL,it will return isValidURL True.If the URL is wrong or the file does not exist,it will return isValidURL false. If the URL is wrong or the file does not exist, that it will hit the catch block and the respective error response will be return back.

Comments or Responses

Login to post response