3 Ekim 2011 Pazartesi

C# http den dosya indirme

        public bool dosyaindir(string dosyaadi, string ProgAd)
        {
            bool bitti = false;
            HttpWebRequest httpIstegi = null;
            HttpWebResponse yanit = null;
            Stream httpStream = null;
            FileStream stream = null;
            string uri = "http://www.mysite.com.tr/update/" + ProgAd + "/" + dosyaadi;
            try
            {

                stream = new FileStream(dosyaadi + "_tmp", FileMode.Create);

                //Alinacak dosyayi bul
                httpIstegi = (HttpWebRequest)HttpWebRequest.Create(new Uri(uri));

                // Yapilacak islem (Download)
                httpIstegi.Method = WebRequestMethods.File.DownloadFile;

                yanit = (HttpWebResponse)httpIstegi.GetResponse();

                httpStream = yanit.GetResponseStream();

                //Buffer uzunlugu
                int bufferUzunlugu = 2048;
                byte[] buffer = new byte[bufferUzunlugu];
                int okumaSayisi = httpStream.Read(buffer, 0, bufferUzunlugu);

                while (okumaSayisi > 0)
                {
                    stream.Write(buffer, 0, okumaSayisi);
                    okumaSayisi = httpStream.Read(buffer, 0, bufferUzunlugu);
                }
                bitti = true;
                return true;
            }
            catch (System.Net.WebException webex)
            {
                //MessageBox.Show("Güncelleme Sırasında Bir Hata Oluştu\nHata:" + webex.Message);
                return false;
            }
            catch (Exception ex)
            {
                // throw ex;
                return false;
            }
            finally
            {
                if (httpStream != null)
                    httpStream.Close();
                if (stream != null)
                    stream.Close();
                if (yanit != null)
                    yanit.Close();
                if (bitti && File.Exists(dosyaadi + "_tmp"))
                {
                    File.Copy(dosyaadi + "_tmp", dosyaadi, true);
                    File.Delete(dosyaadi + "_tmp");
                }
            }
        }

Hiç yorum yok: