GetUrlDownContent函数用来连接服务器下载png文件并保存在本地。现在遇到的问题是,我模拟了一个播放视频的效果。一拖动trackbar就调用valuechanged事件并在picturebox中显示图片。显示图片的这个窗体是主窗体中的一个子窗体。目前整个过程是没问题的。但是当重复代开这个子窗体(显示相同的图片)时,程序就会卡死,而且不报错。请大牛们指教一下小弟。
1.下载图片并保存在本地的代码
public static string GetUrlDownContent(string url, string path)
{
string localPath = string.Empty;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
string downloadName = myrp.Headers["downloadName"];
localPath = path + downloadName;
if (!File.Exists(localPath))
{
System.IO.Stream so = new System.IO.FileStream(localPath, System.IO.FileMode.Create);
System.IO.Stream st = myrp.GetResponseStream();
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
so.Write(by, 0, osize);
osize = st.Read(by, 0, (int)by.Length);
}
so.Close();
st.Close();
myrp.Close();
Myrq.Abort();
}
return localPath;
}
catch (System.Exception e)
{
return null;
}
}
2.拖动trackbar显示图片的代码,DownloadPng经过组装地址最后调用上面的函数下载。
private void trackbarProgress_ValueChanged(object sender, EventArgs e) { showImg(); } //显示当前value所指的图片,trackbarProgress.Value能取到当前值说明已经在list中,不会报错 private void showImg() { if (!listScreenShot[trackbarProgress.Value].IsDownload) listScreenShot[trackbarProgress.Value].LocalPath = mvWrapper.DownloadPng(listScreenShot[trackbarProgress.Value].Id); if (listScreenShot[trackbarProgress.Value].LocalPath != "download failed") { pbViewer.Image = Image.FromFile(listScreenShot[trackbarProgress.Value].LocalPath); listScreenShot[trackbarProgress.Value].IsDownload = true; } else MessageBox.Show("程序异常,请关闭后重启程序。"); }