在C#編程中,下載文件是一種常見的任務。下載文件可以是從互聯網上獲取文件或從本地服務器上獲取文件。無論使用哪種方法,我們都需要了解如何在C#代碼中下載文件。以下是一個包含多種下載方法的詳細討論。
一、使用WebClient類進行下載
WebClient是一個用於發送數據的簡單類,在C#編程中經常用於下載和上傳文件。使用WebClient類下載文件非常簡單,只需以下幾步:
1. 引用System.Net命名空間。
2. 創建一個WebClient對象。
3. 調用DownloadFile方法,並提供要下載的文件的URL和本地文件的路徑。
下面是一個示例代碼:
using System.Net;
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
string url = "http://example.com/image.jpg";
string localPath = @"C:\Downloads\image.jpg";
client.DownloadFile(url, localPath);
}
}
在上面的例子中,首先創建了一個WebClient對象,然後通過調用DownloadFile方法將遠程文件下載到本地。
二、使用HttpWebRequest類進行下載
HttpWebRequest是一個更底層的類,可以用於構建更複雜的HTTP請求,如設置請求頭、發送POST數據等。使用HttpWebRequest下載文件需要以下幾個步驟:
1. 引用System.Net命名空間。
2. 創建一個HttpWebRequest對象。
3. 調用GetResponse方法並獲取響應流。
4. 將響應流寫入本地文件。
下面是一個示例代碼:
using System.Net;
class Program
{
static void Main(string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://example.com/image.jpg");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
byte[] buffer = new byte[4096];
int bytesRead;
string localPath = @"C:\Downloads\image.jpg";
using (FileStream fs = new FileStream(localPath, FileMode.CreateNew))
{
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
}
}
}
}
在上面的例子中,創建一個HttpWebRequest對象,並調用GetResponse方法獲取響應流。然後,我們將響應流讀入緩衝區並將緩衝區寫入本地文件。
三、使用HttpClient類進行下載
HttpClient是C# 5.0及更高版本中引入的新類,可以提供更好的性能和簡化的API。使用HttpClient下載文件與使用WebClient類相似,只需提供文件的URL和本地路徑。下面是一個示例代碼:
using System.Net.Http;
class Program
{
static async Task Main(string[] args)
{
HttpClient client = new HttpClient();
string url = "http://example.com/image.jpg";
string localPath = @"C:\Downloads\image.jpg";
HttpResponseMessage response = await client.GetAsync(url);
using (Stream stream = await response.Content.ReadAsStreamAsync())
using (FileStream fs = new FileStream(localPath, FileMode.CreateNew))
{
await stream.CopyToAsync(fs);
}
}
}
在上面的例子中,我們創建了一個HttpClient對象,並使用GetAsync方法獲取響應。然後,我們將響應流讀入緩衝區並將緩衝區寫入本地文件。
四、下載文件時添加進度條
有時候,我們需要在下載文件時顯示進度條,以便用戶了解下載進度。我們可以使用WebClient或HttpClient類來實現這一點,同時跟蹤downloadProgress事件。
下面是一個WebClient下載帶有進度條的文件的示例代碼:
using System.Net;
class Program
{
static void Main(string[] args)
{
WebClient client = new WebClient();
string url = "http://example.com/image.jpg";
string localPath = @"C:\Downloads\image.jpg";
client.DownloadProgressChanged += (sender, e) =>
{
Console.WriteLine($"Downloaded {e.BytesReceived} of {e.TotalBytesToReceive} bytes. {e.ProgressPercentage}% complete.");
};
client.DownloadFileAsync(new Uri(url), localPath);
}
}
在上面的代碼中,我們綁定了DownloadProgressChanged事件,以跟蹤下載的進度。當下載進度發生變化時,事件處理程序將被調用,並顯示下載的字節數和已完成的百分比。
在HttpClient中,我們可以使用Progress類來跟蹤下載進度。下面是一個示例代碼:
using System.Net.Http;
class Program
{
static async Task Main(string[] args)
{
HttpClient client = new HttpClient();
string url = "http://example.com/image.jpg";
string localPath = @"C:\Downloads\image.jpg";
var progress = new Progress<long>();
progress.ProgressChanged += (sender, bytesDownloaded) =>
{
Console.WriteLine($"Downloaded {bytesDownloaded} bytes.");
};
await client.DownloadFileWithProgressAsync(url, localPath, progress);
}
}
static class HttpClientExtensions
{
public static async Task DownloadFileWithProgressAsync(this HttpClient client, string requestUri, string filePath, IProgress<long> progress = null)
{
using (HttpResponseMessage response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead))
using (Stream streamToReadFrom = await response.Content.ReadAsStreamAsync())
{
string fileToWriteTo = filePath;
string directoryName = Path.GetDirectoryName(fileToWriteTo);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
using (Stream streamToWriteTo = File.Open(fileToWriteTo, FileMode.Create))
{
await streamToReadFrom.CopyToAsync(streamToWriteTo, 4096, progress);
}
}
}
}
在上面的代碼中,我們創建了一個名為progress的Progress<long>對象,並綁定了ProgressChanged事件以顯示下載進度。DownloadFileWithProgressAsync方法接收一個名為progress的參數,以便我們與進度條交互。在方法內部,我們使用HttpResponseMessage獲取響應流,並將其寫入本地文件。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/303437.html