Sadia
Sadia

Reputation: 181

how can i check if there is some error in the http link, and then proceed?

I have written an action method in mvc4 which downloads the file from a link and then uploads data into database from that file. I am using Web-client class to download the file. Now at this stage i want to know if there is any appropriate method to check error in the url and stop the downloading of file keeping the previous file intact at the mapped place.here is how i am downloading the file into my folder:

public class testController : Controller
    {

        public class MyWebClient : WebClient
        {
            protected override WebRequest GetWebRequest(Uri address)
            {
                var req = base.GetWebRequest(address);
                req.Timeout = 15000000;
                return req;
            }
        }


        public ActionResult index()
        {
            System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempBrdcepPSC/PscData"));
            foreach (FileInfo csvfile in di.GetFiles())

            {
                csvfile.Delete();
            }
            MyWebClient webClient = new MyWebClient();
            webClient.DownloadFile("https://www.google.com.pk/", Server.MapPath("~/App_Data/New_folder/Summary.csv"));



            return View();
        }

    }

Upvotes: 2

Views: 509

Answers (4)

er-sho
er-sho

Reputation: 9771

Now at this stage i want to know if there is any appropriate method to check error in the url

You can use following method to check your Uri valid or not

public static bool URLValidatorMethod(string strURL)
{
   Uri uri;
   return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uri);
}

Q) What TryCreate actually do?

A) Creates a new System.Uri using the specified System.String instance and a System.UriKind. and returns a System.Boolean value that is true if the System.Uri was successfully created otherwise, false.

You may check that is there url have http or https by using

return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uri) && uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;

OR

public static bool URLValidatorMethod(string strURL)
{
     return Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute); ;
}

Q) What IsWellFormedUriString actually do?

A) Indicates whether the string is well-formed by attempting to construct a URI with the string and ensures that the string does not require further escaping.

stop the downloading of file keeping the previous file intact at the mapped place

First check is your url valid or not by above method and if valid then save it to folder otherwise ignore it

By this your previous downloaded file will not affect anymore and its safe on your mapped place like

string url = "https://www.google.com.pk/";

if (URLValidatorMethod(url))
{
    webClient.DownloadFile(url, Server.MapPath("~/App_Data/New_folder/Summary.csv"));
}
else
{
    //Do code here that you want
}

Edited:

try
{
    string url = "https://www.google.com.pk/";

    if (URLValidatorMethod(url))
    {
        webClient.DownloadFile(url, Server.MapPath("~/App_Data/New_folder/Summary.csv"));
    }
    else
    {
        //Do code here that you want
    }
}
catch (Exception)
{
    //Do code here if you want to execute if exception occurred
}
finally
{
    //Do the code here that you want either exception occurred or not
    //Means this code run always if exception comes or not
}

OR

You may modify your catch block if you write to code if specific type of exception or error occured

catch (Exception ex)
{
    //You may check any particular exception and write your code
    if (ex.GetType() == typeof(ArgumentNullException))
    {
        //Do code here 
    }
    else
    if (ex.GetType() == typeof(WebException))
    {
        //Do code here 
    }
    else
    if (ex.GetType() == typeof(NotSupportedException))
    {
        //Do code here 
    }

 }

Edited:

In reference to above detailed answer this is the solution that worked for me, if it helps somebody:

Create a temporary folder download your file there and if there is no error came during downloading it will copy file from temp folder to original place and do the rest of the work.otherwise if there comes any error an email will be sent indicating error while the rest of code will execute without causing the error in actual flow of code.

[HttpGet]
public ActionResult index(int OpCode)
{

        try
        {
            System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder"));
            foreach (FileInfo csvfile in di.GetFiles())

            {
                csvfile.Delete();
            }
            MyWebClient webClient1 = new MyWebClient();
            webClient1.DownloadFile("http://example.php", Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv"));
        }
        catch (Exception)
        {
            return RedirectToAction("ImportSendMail");

        }

        var absolutePath = HttpContext.Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/" + "Summary.csv");
        if (System.IO.File.Exists(absolutePath))
        {

            System.IO.DirectoryInfo di2 = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData"));
            foreach (FileInfo csvfile in di2.GetFiles())

            {
                csvfile.Delete();
            }

                String sourceFile = Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv");
                String destFile = Server.MapPath("~/App_Data/TempPSC/PscData/abc" + ".csv");
                        System.IO.File.Copy(sourceFile, destFile, true);


        }

        {
           //Rest of the default code that you want to run

        }

    return View();

}

Upvotes: 2

Sadia
Sadia

Reputation: 181

Create a temporary folder download your file there and if there is no error came during downloading it will copy file from temp folder to original place and do the rest of the work.otherwise if there comes any error an email will be sent indicating error while the rest of code will execute without causing the error in actual flow of code.

 [HttpGet]
        public ActionResult index(int OpCode)
        {

                try
                {
                    System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder"));
                    foreach (FileInfo csvfile in di.GetFiles())

                    {
                        csvfile.Delete();
                    }
                    MyWebClient webClient1 = new MyWebClient();
                    webClient1.DownloadFile("http://example.php", Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv"));
                }
                catch (Exception)
                {
                    return RedirectToAction("ImportSendMail");

                }

                var absolutePath = HttpContext.Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/" + "Summary.csv");
                if (System.IO.File.Exists(absolutePath))
                {

                    System.IO.DirectoryInfo di2 = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData"));
                    foreach (FileInfo csvfile in di2.GetFiles())

                    {
                        csvfile.Delete();
                    }

                        String sourceFile = Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv");
                        String destFile = Server.MapPath("~/App_Data/TempPSC/PscData/abc" + ".csv");
                        System.IO.File.Copy(sourceFile, destFile, true);


                }

              {
              //Rest of the default code that you want to run

              }

            return View();

        }

Upvotes: 0

Hiren Patel
Hiren Patel

Reputation: 1157

You can check HTTP Error in this way, this function also check for URL Exist or not.

private bool HttpValidation(string URL)
{
    Uri urlToCheck = new Uri(URL);
    WebRequest request = WebRequest.Create(urlToCheck);
    request.Timeout = 15000;

    WebResponse response;
    try
    {
        response = request.GetResponse();
    }
    catch (Exception)
    {
        return false; //url does not exist or have some error
    }

    return true;
}

URL must be provided in http:// or https:// form.

eg.

if(HttpValidation("https://www.google.com.pk"))
{
 webClient.DownloadFile("https://www.google.com.pk/",Server.MapPath("~/App_Data/New_folder/Summary.csv"));
}

if you want check that url is valid or not then you can try

Uri uriResult;
bool result = Uri.TryCreate(uriName, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps); 

I hope this will help you.

Upvotes: 1

Abhishek Vyas
Abhishek Vyas

Reputation: 744

Checking the error: The DownloadFile method throws three exceptions Ref

  • ArgumentNullException
  • WebException (this should fit in your use case)
  • NotSupportedException

Put your code in try catch block.

Keeping the previous file intact: I would suggest, first download the file in temporary folder and if there are not exception then replace previous file from the recent file which you just downloaded in temp folder.

Happy Coding!!!

Upvotes: 1

Related Questions