【发布时间】:2011-03-14 19:50:26
【问题描述】:
我正在构建一个应用程序来从互联网上检索图像。即使它工作正常,但在应用程序中使用 try-catch 语句时它很慢(在错误的 URL 上)。
(1) 这是验证 URL 和处理错误输入的最佳方法 - 还是我应该改用正则表达式(或其他方法)?
(2) 为什么我没有在文本框中指定http://,应用程序会尝试在本地查找图片?
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
编辑:
我尝试了 Panagiotis Kanavos 建议的解决方案(感谢您的努力!),但如果用户输入 http://,它只会在 if-else 语句中被捕获,仅此而已。更改为 UriKind.Absolute 也会捕获空字符串!越来越近 :)
目前的代码:
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);
}
我一定是在这里做错了什么。 :(
【问题讨论】:
-
您怎么知道
ArgumentException或WebException表示网址有问题? -
这是我调试时遇到的异常。但我同意 - 从 Internet 下载的异常类型可能更多。