.Net  

private bool DownLoad(string downloadUrl,string savepath)
        {
            Stream responseStream = null;
            FileStream fileStream = null;
            StreamReader reader = null;
            try
            {
                FtpWebRequest downloadRequest =(FtpWebRequest)WebRequest.Create(downloadUrl);
                downloadRequest.Credentials = new NetworkCredential(txtuser.Text.Trim(), txtpwd.Text.Trim());
                FtpWebResponse downloadResponse =(FtpWebResponse)downloadRequest.GetResponse();
                responseStream = downloadResponse.GetResponseStream();
                string fileName =Path.GetFileName(downloadRequest.RequestUri.AbsolutePath);

                if (fileName.Length == 0)
                {
                    reader = new StreamReader(responseStream);
                    Console.WriteLine(reader.ReadToEnd());
                }
                else
                {
                    fileStream = File.Create(savepath+fileName);
                    byte[] buffer = new byte[1024];
                    int bytesRead;
                    while (true)
                    {
                        bytesRead = responseStream.Read(buffer, 0, buffer.Length);
                        if (bytesRead == 0)
                            break;
                        fileStream.Write(buffer, 0, bytesRead);
                    }
                }
                return true;
            }
            catch (UriFormatException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            catch (IOException ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                else if (responseStream != null)
                    responseStream.Close();
                if (fileStream != null)
                    fileStream.Close();
            }
        }

 

posted on 2007-03-28 19:23  东方新秀  阅读(214)  评论(0编辑  收藏  举报