c#下载文件的方法有哪些

   2025-02-05 8850
核心提示:在C#中下载文件有多种方法:使用WebClient类:可以使用WebClient类的DownloadFile方法来下载文件。以下是一个示例:string url =

在C#中下载文件有多种方法:

使用WebClient类:可以使用WebClient类的DownloadFile方法来下载文件。以下是一个示例:
string url = "http://example.com/file.txt";string savePath = "C:\\Downloads\\file.txt";using (WebClient client = new WebClient()){    client.DownloadFile(url, savePath);}
使用HttpClient类:可以使用HttpClient类的GetAsync方法来下载文件。以下是一个示例:
string url = "http://example.com/file.txt";string savePath = "C:\\Downloads\\file.txt";using (HttpClient client = new HttpClient()){    HttpResponseMessage response = await client.GetAsync(url);    response.EnsureSuccessStatusCode();    using (Stream contentStream = await response.Content.ReadAsStreamAsync(),                  stream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true))    {        await contentStream.CopyToAsync(stream);    }}
使用WebRequest和WebResponse类:可以使用WebRequest类发送HTTP请求,并使用WebResponse类获取响应数据。以下是一个示例:
string url = "http://example.com/file.txt";string savePath = "C:\\Downloads\\file.txt";WebRequest request = WebRequest.Create(url);WebResponse response = request.GetResponse();using (Stream responseStream = response.GetResponseStream(),              stream = new FileStream(savePath, FileMode.Create, FileAccess.Write, FileShare.None, 8192, true)){    byte[] buffer = new byte[8192];    int bytesRead;    while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)    {        stream.Write(buffer, 0, bytesRead);    }}

以上是三种常用的下载文件的方法,你可以根据自己的需求选择适合的方法。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言