PDA

View Full Version : سوال: دریافت عکس توسط Webclient



trojan001
جمعه 27 دی 1392, 17:58 عصر
سلام دوستان یه سوال داشتم ببینید من با وب کلاینت می زنم یه عکسی رو از یه ادرسی داونلود کنه بد تو پیکچر باکس نشون بده حالا بعضی مواقع این صفحه not found می شه چیزی باس داونلود نداره بد سافت ارورو می ده کهThe remote server returned an error: (404) Not Found. خوب چی کار کنم که اینجوری شد سافت به مشکل نخوره ؟


WebClient avatar = new WebClient();
avatar.DownloadFile("http://avatar.nimbuzz.com/getAvatar?jid=" + textBox1.Text + "@nimbuzz.com", "reject.jpg");
pictureBox1.ImageLocation = "reject.jpg";
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

بیبن جا textbox1.text اگه یزاری poya سافت عکس پیدا نمی کنه و ارور می ده ولی اگه بزاری poya01 عکس پیدا می کنه و ارور نمی ده تو مروگر بزنید اینو معلومه تفاوتش

Mahmoud.Afrad
جمعه 27 دی 1392, 21:25 عصر
به خاطر اینه که چنین آدرسی وجود نداره(در مرورگر وارد کنی همین پیغام رو میگیری.
با try ... catch کنترل کن:

pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
Image img = null;
try
{
WebRequest req = WebRequest.Create("http://avatar.nimbuzz.com/getAvatar?jid=" + textBox1.Text + "@nimbuzz.com");
WebResponse res = req.GetResponse();
Stream stream = res.GetResponseStream();
img = Image.FromStream(stream);
}
catch (WebException wex)
{
if (wex.Message.Contains("(404)"))
{
img = new Bitmap(pictureBox1.Width, pictureBox1.Height);
Graphics g = Graphics.FromImage(img);
g.FillRectangle(Brushes.Black, 0, 0, img.Width, img.Height);
string messageStr = "عکس یافت نشد";
Font font = new Font("Tahoma", 14);
SizeF stringSize = g.MeasureString(messageStr, font);
int x = (int)(img.Width / 2 - stringSize.Width / 2);
int y = (int)(img.Height / 2 - stringSize.Height / 2);
Point stringLocation = new Point(x, y);
g.DrawString(messageStr, font, Brushes.White, stringLocation);
}
else
{
img = null;
}
}
finally
{
pictureBox1.Image = img;
}