"Invalid URI: The format of the URI could not be determined" Error in C#


I am trying to run the below code in my asp.net MVC web-application, to get the URL of first image(<img>) in the HTML string, using the code below

       public static List<Uri> FetchLinksFromSource(string htmlSource)
        {
            List<Uri> links = new List<Uri>();
            string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m in matchesImgSrc)
            {
                string href = m.Groups[1].Value;
                links.Add(new Uri(href)); //getting error here
            }
            return links;
        }

but I am getting this error "Invalid URI: The format of the URI could not be determined" when I run this code, here is the image of the error

Invalid URI The format of the URI could not be determined.png

How is that not a valid URI format? and how can resolve it?


Asked by:- bhanu
1
: 103 At:- 9/16/2017 9:56:59 AM
C# asp-net-mvc invalid-uri asp.net






1 Answers
profileImage Answered by:- neena

You are getting the error of Invalid URI because you are passing a string here, which may or may not have complete URL with https or http (with protocol) string

string href = m.Groups[1].Value;

So you need to change the above code and use it like

public static List<Uri> FetchLinksFromSource(string htmlSource)
        {
            List<Uri> links = new List<Uri>();
            string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
            MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            foreach (Match m in matchesImgSrc)
            {
                string href = m.Groups[1].Value; 
                 //get Request Context
                var request = HttpContext.Current.Request; 

                // Get url scheme with domain name(Auhtority) https://foo.com
                Uri serverUri = new Uri(request.Url.Scheme+"://"+ request.Url.Authority);

                // get the relative uri (/test.html)
                Uri relativeUri = new Uri(href, UriKind.Relative);

                // Get complete URi details
                Uri fullUri = new Uri(serverUri, relativeUri);

                //Now add it in Link
                links.Add(fullUri);
            }
            return links;
        }

I have commented out the code, to explain its meaning, I hope this helps, thanks

1
At:- 9/16/2017 11:11:04 AM
good answer with details, as needed 1
By : Vinnu - at :- 9/21/2017 10:18:16 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use
Amazon Deals

Jobs from Indeed