我正在尝试显示一个显示标签的表单,例如“更新,此窗口将在更新完成后关闭”以下载一些图像文件。我把它放在我的表格上。
private void frmExtraUpdater_Shown(object sender, EventArgs e)
{
for (int i = 1; i < 8; i++)
{
string _EmoticonURL = String.Format("https://dl.dropboxusercontent.com/u/110636189/MapleEmoticons/f{0}.bmp", i);
WebRequest requestPic = WebRequest.Create(_EmoticonURL);
WebResponse responsePic = requestPic.GetResponse();
Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error
webImage.Save(Application.StartupPath + @"\Images\f" + i + ".bmp");
}
}
然而..一旦显示表单,标签甚至不显示,因为它没有加载它(它坚持下载图像。我希望它显示标签,然后才开始下载)。
另一个问题是它抛出了“GDI +中发生了一般错误”。在webImgae.Save部分由于某种原因。
为什么?
哦,如果文件夹“图片”不存在,它会自动创建吗?
谢谢!
答案 0 :(得分:1)
这是Jon Skeet的建议:
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(String.Format("https://dl.dropboxusercontent.com/u/110636189/MapleEmoticons/f{0}.bmp", i), Application.StartupPath + @"\Images\f" + i + ".bmp");
使用后台工作程序更新任何UI组件
BackgroundWorker backTask = new BackgroundWorker();
public frmExtraUpdater()
{
backTask.DoWork += backTask_DoWork;
backTask.RunWorkerCompleted += backTask_RunWorkerCompleted;
}
private void frmExtraUpdater_Shown(object sender, EventArgs e)
{
yourLabel.Text = "Downloading";
backTask.RunWorkerAsync();
}
void backTask_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i < 8; i++)
{
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(String.Format("https://dl.dropboxusercontent.com/u/110636189/MapleEmoticons/f{0}.bmp", i), Application.StartupPath + @"\Images\f" + i + ".bmp");
backTask.ReportProgress(i * (100 / 8), String.Format("https://dl.dropboxusercontent.com/u/110636189/MapleEmoticons/f{0}.bmp", i));
}
}
void backTask_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
yourLabel.Text = "Downloading" + e.UserState.ToString();
}
void backTask_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Close();
}
答案 1 :(得分:0)
您应该使用async方法,使用webrequest async api(如果使用.net 4.5或sup)或者在后台线程中下载图像以避免ui线程阻塞。
您可以尝试:
private void frmExtraUpdater_Shown(object sender, EventArgs e)
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (o, d) =>
{
saveImages();
};
worker.RunWorkerCompleted += (o, f) =>
{
this.Close();
};
worker.RunWorkerAsync();
}
private void saveImages()
{
for (int i = 1; i < 8; i++)
{
string _EmoticonURL = String.Format("https://dl.dropboxusercontent.com/u/110636189/MapleEmoticons/f{0}.bmp", i);
WebRequest requestPic = WebRequest.Create(_EmoticonURL);
WebResponse responsePic = requestPic.GetResponse();
Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error
webImage.Save(Application.StartupPath + @"\Images\f" + i + ".bmp");
}
}