首页 新闻 会员 周边 捐助

使用new System.IO.FileStream()创建文件后,反复打开卡死。

0
悬赏园豆:30 [已关闭问题] 关闭于 2015-04-18 23:43

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("程序异常,请关闭后重启程序。");
        }

 

Mr_4的主页 Mr_4 | 初学一级 | 园豆:108
提问于:2014-11-27 16:22
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册