在C#中实现HTTP下载文件的方法是使用HttpClient
类发送HTTP请求并下载文件。以下是一个简单的示例代码:
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string url = "https://example.com/file.jpg";
string savePath = "C:\\path\\to\\save\\file.jpg";
using (var client = new HttpClient())
{
var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
using (var fileStream = System.IO.File.Create(savePath))
{
await response.Content.CopyToAsync(fileStream);
}
Console.WriteLine("File downloaded successfully.");
}
else
{
Console.WriteLine($"Failed to download file. Status code: {response.StatusCode}");
}
}
}
}
在上面的示例中,我们首先创建一个HttpClient
实例,然后发送一个GET请求以下载文件。如果请求成功,就将响应内容写入到本地文件中。最后,我们输出下载结果。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/942915.html