2009-02-08 19 views
56

Windows başvuru formu bir web sitesinden bir dosya indirmek ve belirli bir dizine koymak mümkün mü?C# bir web sitesinden bir dosya nasıl indirilir #

+0

neyi taşıma iyisini yapabiliriz? FTP? HTTP? –

+0

Mitch'in yorumu en doğru ve en doğru cevaptır, lol! – Cerebrus

+0

.net konusunda yeniyseniz, MSDN belgelerinin aranmasına yardımcı olmayı öneririm. Bunu başarmak istediğiniz şeylere bakın, bu ad alanına hangi adın sığabileceğini öğrenin ve bunu yapabilecek bir sınıf olup olmadığını görün :) – shahkalpesh

cevap

103

:

using System.Net; 
//... 
WebClient Client = new WebClient(); 
Client.DownloadFile("http://i.stackoverflow.com/Content/Img/stackoverflow-logo-250.png", @"C:\folder\stackoverflowlogo.png"); 
+0

Teşekkür ederim, Bu tam istediğim gibi çalıştı! – S3THST4

+0

Dosyayı, uygulama yükleme dizinine göre bir klasöre nasıl indirirsiniz? (indirme yolunuz sabit kodlandığından) – RPDeshaies

+2

@ Tareck117 AppDomain.CurrentDomain.BaseDirectory + "myname" – Luntri

72

Kullanım WebClient.DownloadFile:

using (WebClient client = new WebClient()) 
{ 
    client.DownloadFile("http://csharpindepth.com/Reviews.aspx", 
         @"c:\Users\Jon\Test\foo.txt"); 
} 
+24

SKEEEEEEEEEEEEEET! – FlySwat

+0

IDisposable; -p Ancak (bir "kullanarak") yazmayı denemek için tam olarak geldiğini unutmayın ... –

+0

Ah, pedants tarafından normal hizmet sürdürülür; -p –

12

Tabii, sadece HttpWebRequest kullanın. Eğer kurmak HttpWebRequest sahip olduktan sonra

, siz (. mime bağlı BinaryWriter veya TextWriter Ya) bir dosyaya StreamWriter yanıt akışı kaydedebilir ve sabit diskinizde bir dosya var.

DÜZENLEME: WebClient hakkında bilgi edinin. Dosyanızı almak için sadece GET'u kullanmanız gerekmediği sürece iyi çalışır. Sitenin size POST bilgilerini girmesini gerektiriyorsa, bir HttpWebRequest kullanmanız gerekecek, dolayısıyla cevabımı bırakıyorum. WebClient class ile

+0

Yavaş bir HD'den geri okumak istemiyorum .. https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx – Dan

0

bu örneği deneyin:

uygulama şu yapılır
public void TheDownload(string path) 
{ 
    System.IO.FileInfo toDownload = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(path)); 

    HttpContext.Current.Response.Clear(); 
    HttpContext.Current.Response.AddHeader("Content-Disposition", 
      "attachment; filename=" + toDownload.Name); 
    HttpContext.Current.Response.AddHeader("Content-Length", 
      toDownload.Length.ToString()); 
    HttpContext.Current.Response.ContentType = "application/octet-stream"; 
    HttpContext.Current.Response.WriteFile(patch); 
    HttpContext.Current.Response.End(); 
} 

:

TheDownload("@"c:\Temporal\Test.txt""); 

Kaynak: http://www.systemdeveloper.info/2014/03/force-downloading-file-from-c.html

0

Ayrıca sınıfında DownloadFileAsync yöntemini kullanabilirsiniz. Belirtilen URI ile yerel bir dosyaya kaynağı indirir. Ayrıca bu yöntem çağıran parçacığı engellemez.

Örnek: Daha fazla bilgi için

webClient.DownloadFileAsync(new Uri("http://www.example.com/file/test.jpg"), "test.jpg"); 

: Masaüstünden Bir web sitesinden dosyayı indirin için bu kodu kullanabilirsiniz

http://csharpexamples.com/download-files-synchronous-asynchronous-url-c/

12

Dosya yükleme sırasında durumu bilmeniz veya istekte bulunmadan önce kimlik bilgilerini kullanmanız gerekebilir.aşağıdaki gibi uygulanan

Uri ur = new Uri("http://remotehost.do/images/img.jpg"); 

using (WebClient client = new WebClient()) { 
    //client.Credentials = new NetworkCredential("username", "password"); 
    String credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes("Username" + ":" + "MyNewPassword")); 
    client.Headers[HttpRequestHeader.Authorization] = $"Basic {credentials}"; 

    client.DownloadProgressChanged += WebClientDownloadProgressChanged; 
    client.DownloadDataCompleted += WebClientDownloadCompleted; 
    client.DownloadFileAsync(ur, @"C:\path\newImage.jpg"); 
} 

ve geri arama işlevlerini:

void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) 
{ 
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage); 

    // updating the UI 
    Dispatcher.Invoke(() => { 
     progressBar.Value = e.ProgressPercentage; 
    }); 
} 

void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e) 
{ 
    Console.WriteLine("Download finished!"); 
} 

Lambda gösterimi: Burada

bu seçenekleri kapsayan bir örnektir olayları

işlemek için diğer olası seçenek
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(delegate(object sender, DownloadProgressChangedEventArgs e) { 
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage); 

    // updating the UI 
    Dispatcher.Invoke(() => { 
     progressBar.Value = e.ProgressPercentage; 
    }); 
}); 

client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(delegate(object sender, DownloadDataCompletedEventArgs e){ 
    Console.WriteLine("Download finished!"); 
}); 

Biz

client.DownloadProgressChanged += (object sender, DownloadProgressChangedEventArgs e) => 
{ 
    Console.WriteLine("Download status: {0}%.", e.ProgressPercentage); 

    // updating the UI 
    Dispatcher.Invoke(() => { 
     progressBar.Value = e.ProgressPercentage; 
    }); 
}; 

client.DownloadDataCompleted += (object sender, DownloadDataCompletedEventArgs e) => 
{ 
    Console.WriteLine("Download finished!"); 
}; 

Ya

client.DownloadProgressChanged += (o, e) => 
{ 
    Console.WriteLine($"Download status: {e.ProgressPercentage}%."); 

    // updating the UI 
    Dispatcher.Invoke(() => { 
     progressBar.Value = e.ProgressPercentage; 
    }); 
}; 

client.DownloadDataCompleted += (o, e) => 
{ 
    Console.WriteLine("Download finished!"); 
}; 
+0

"Async void" yerine "async Task" işlevini kullanmak istiyorsanız, bu webClient.DownloadFileTaskAsync (...) 'yı kullanan [bu yanıt] 'a (http://stackoverflow.com/a/16514441/2816057) bakın. 'DownloadDataCompleted' olayına gerek yok –

İlgili konular