雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

.NET Core下载保存图片

2024-08-22 31

当你想要在 .NET Core 中下载并保存图片时,你可以使用 .NET Core 提供的 HttpClient 类来下载图片,并使用 FileStream 或其他文件流来保存图片到本地。以下是一个简单的示例代码,演示了如何在 .NET Core 中下载并保存图片:

using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace ImageDownloader
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string imageUrl = "https://example.com/image.jpg"; // 图片 URL
            string localFilePath = @"C:\Path\To\Save\Image.jpg"; // 本地保存路径

            using (HttpClient httpClient = new HttpClient())
            {
                try
                {
                    // 下载图片
                    HttpResponseMessage response = await httpClient.GetAsync(imageUrl);
                    if (response.IsSuccessStatusCode)
                    {
                        // 读取图片数据
                        byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();

                        // 保存图片到本地文件
                        await File.WriteAllBytesAsync(localFilePath, imageBytes);

                        Console.WriteLine("图片已保存到:" + localFilePath);
                    }
                    else
                    {
                        Console.WriteLine("下载图片失败:" + response.ReasonPhrase);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发生异常:" + ex.Message);
                }
            }
        }
    }
}

这段代码使用 HttpClient 发起 HTTP GET 请求来下载指定 URL 的图片,并使用 File.WriteAllBytesAsync 方法将图片数据保存到本地文件。请确保替换 imageUrl 和 localFilePath 变量为实际的图片 URL 和本地保存路径。

此代码片段假设你已经安装了 System.Net.Http 命名空间。你可以在 .NET Core 项目中使用这段代码来下载和保存图片到指定路径。

更新于:28天前
赞一波!4

文章评论

全部评论