c#异常的处理

public static void DownIMG(String uri, String path)
        {
            WebResponse response = null;
            Stream reader = null;
            FileStream writer = null;
            try
            {
                WebRequest request = WebRequest.Create(uri);
                request.Timeout = Timeout.Infinite;
                response = request.GetResponse();

                String type = response.ContentType;
                if (type.StartsWith("image/png"))
                {
                    path += ".png";
                }
                else
                {
                    path += ".jpg";
                }

                reader = response.GetResponseStream();
                writer = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                byte[] buff = new byte[512];
                int c = 0; //实际读取的字节数
                while ((c = reader.Read(buff, 0, buff.Length)) > 0)
                {
                    writer.Write(buff, 0, c);
                }
            }
            catch (Exception e)
            {
                throw e;//在这里抛出异常是可以的,finally里面的代码依然会执行,会先运行到这里,再运行finally,再运行调用该方法的try
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                }
                if (reader != null)
                {
                    reader.Close();
                    reader.Dispose();
                }
                if (response != null)
                {
                    response.Close();
                }
            }
        }

 

posted on 2013-01-09 15:24  雨渐渐  阅读(122)  评论(0编辑  收藏  举报

导航