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(); } } }