I'm building an application to retrieve an image from internet. Even though it works fine, it is slow (on wrong given URL) when using try-catch statements in the application.
(1) Is this the best way to verify URL and handle wrong input - or should I use Regex (or some other method) instead?
(2) Why does the application try to find images locally if I don't specify http:// in the textBox?
private void btnGetImage_Click(object sender, EventArgs e)
{
String url = tbxImageURL.Text;
byte[] imageData = new byte[1];
using (WebClient client = new WebClient())
{
try
{
imageData = client.DownloadData(url);
using (MemoryStream ms = new MemoryStream(imageData))
{
try
{
Image image = Image.FromStream(ms);
pbxUrlImage.Image = image;
}
catch (ArgumentException)
{
MessageBox.Show("Specified image URL had no match",
"Image Not Found", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
}
}
catch (ArgumentException)
{
MessageBox.Show("Image URL can not be an empty string",
"Empty Field", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
catch (WebException)
{
MessageBox.Show("Image URL is invalid.\nStart with http:// " +
"and end with\na proper image extension", "Not a valid URL",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
} // end of outer using statement
} // end of btnGetImage_Click
EDIT:
I tried the suggested solution by Panagiotis Kanavos (thank you for your effort!), but it only gets caught in the if-else statement if the user enters http://
and nothing more. Changing to UriKind.Absolute catches empty strings as well! Getting closer :)
The code as of now:
private void btnGetImage_Click(object sender, EventArgs e)
{
String url = tbxImageURL.Text;
byte[] imageData = new byte[1];
Uri myUri;
// changed to UriKind.Absolute to catch empty string
if (Uri.TryCreate(url, UriKind.Absolute, out myUri))
{
using (WebClient client = new WebClient())
{
try
{
imageData = client.DownloadData(myUri);
using (MemoryStream ms = new MemoryStream(imageData))
{
imageData = client.DownloadData(myUri);
Image image = Image.FromStream(ms);
pbxUrlImage.Image = image;
}
}
catch (ArgumentException)
{
MessageBox.Show("Specified image URL had no match",
"Image Not Found", MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch (WebException)
{
MessageBox.Show("Image URL is invalid.\nStart with http:// " +
"and end with\na proper image extension",
"Not a valid URL",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
else
{
MessageBox.Show("The Image Uri is invalid.\nStart with http:// " +
"and end with\na proper image extension", "Uri was not created",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
I must be doing something wrong here. :(
Some examples when using Uri to test a valid URL fails
I Was surprised to have all this nonsense appear in my listview after validating with the above. But it all passes the validation test.
Now I add the following after the above validation
My solution:
you can use the function
Uri.TryCreate
As Panagiotis Kanavos suggested if you like to test and create a url or you can useUri.IsWellFormedUriString
function as suggested by Todd Menier if you just wanted to test the validity of Url. this can by handy if you are just validating user input for now and need to create url some time later in life time of your application.**But my post is for the People, like myself :( , still hitting their heads against .net 1.1 **
both above methods were introduced in .net 2.0 so you guys still have to use try catch method, which, in my opinion, is still far better than using regular expression.
Use Uri.TryCreate to create a new Uri object only if your url string is a valid URL. If the string is not a valid URL, TryCreate returns false.
UPDATE
TryCreate or the Uri constructor will happily accept strings that may appear invalid, eg "Host: www.stackoverflow.com","Host:%20www.stackoverflow.com" or "chrome:about". In fact, these are perfectly valid URIs that specify a custom scheme instead of "http".
The documentation of the Uri.Scheme property provides more examples like "gopher:" (anyone remember this?), "news", "mailto", "uuid".
An application can register itself as a custom protocol handler as described in MSDN or other SO questions, eg How do I register a custom URL protocol in Windows?
TryCreate doesn't provide a way to restrict itself to specific schemes. The code needs to check the Uri.Scheme property to ensure it contains an acceptable value
UPDATE 2
Passing a weird string like
"></script><script>alert(9)</script>
will returntrue
and construct a relative Uri object. Calling Uri.IsWellFormedOriginalString will return false though. So you probably need to callIsWellFormedOriginalString
if you want to ensure that relative Uris are well formed.On the other hand, calling
TryCreate
withUriKind.Absolute
will return false in this case.Interestingly, Uri.IsWellFormedUriString calls TryCreate internally and then returns the value of
IsWellFormedOriginalString
if a relative Uri was created.I wanted to check if the url also contains a domain extension, it needs to be a valid website url.
This is what i came up with:
I've tested the code with linqpad:
Results:
Hi you validate https http,ftp,sftp,ftps,any thing starting with www.