Download all images from blogger using asp.net mvc

 Sure, you can modify the code to save images to a folder on your D drive and organize them into subfolders based on the first image's name. Here's how you can do it:


```csharp asp.net mvc5

using System;

using System.Collections.Generic;

using System.IO;

using System.Net.Http;

using System.Threading.Tasks;

using System.Web.Mvc;

using HtmlAgilityPack;


namespace YourNamespace.Controllers

{

    public class ImageController : Controller

    {

        // GET: Image

        public async Task<ActionResult> Index()

        {

            // List of URLs to fetch

            List<string> urls = new List<string>

            {

                "https://example.com/page1",

                "https://example.com/page2",

                // Add more URLs as needed

            };


            foreach (var url in urls)

            {

                // Fetch HTML content from URL

                string htmlContent = await GetHtmlContent(url);


                // Parse HTML content to extract image URLs

                List<string> imageUrls = GetImageUrls(htmlContent);


                // Save images to folder

                await SaveImagesToFolder(imageUrls);

            }


            return View();

        }


        private async Task<string> GetHtmlContent(string url)

        {

            using (var client = new HttpClient())

            {

                // Fetch HTML content from URL

                HttpResponseMessage response = await client.GetAsync(url);

                response.EnsureSuccessStatusCode();

                string htmlContent = await response.Content.ReadAsStringAsync();

                return htmlContent;

            }

        }


        private List<string> GetImageUrls(string htmlContent)

        {

            var imageUrls = new List<string>();


            // Load HTML content into HtmlDocument

            var htmlDocument = new HtmlDocument();

            htmlDocument.LoadHtml(htmlContent);


            // XPath to find img elements

            var imgNodes = htmlDocument.DocumentNode.SelectNodes("//img");


            if (imgNodes != null)

            {

                foreach (var imgNode in imgNodes)

                {

                    // Get the src attribute value of img elements

                    string imageUrl = imgNode.GetAttributeValue("src", "");

                    imageUrls.Add(imageUrl);

                }

            }


            return imageUrls;

        }


        private async Task SaveImagesToFolder(List<string> imageUrls)

        {

            // Create a folder on D drive based on the first image's name

            if (imageUrls.Count > 0)

            {

                string firstImageUrl = imageUrls[0];

                string folderName = Path.GetFileNameWithoutExtension(firstImageUrl);

                string folderPath = Path.Combine("D:\\", folderName);

                Directory.CreateDirectory(folderPath);


                // Download and save images to the created folder

                using (var client = new HttpClient())

                {

                    foreach (var imageUrl in imageUrls)

                    {

                        try

                        {

                            HttpResponseMessage response = await client.GetAsync(imageUrl);

                            response.EnsureSuccessStatusCode();

                            byte[] imageBytes = await response.Content.ReadAsByteArrayAsync();

                            string imageName = Path.GetFileName(new Uri(imageUrl).LocalPath);

                            string imagePath = Path.Combine(folderPath, imageName);

                            System.IO.File.WriteAllBytes(imagePath, imageBytes);

                        }

                        catch (Exception ex)

                        {

                            // Handle exceptions, e.g., image download failed

                            Console.WriteLine($"Error downloading image from {imageUrl}: {ex.Message}");

                        }

                    }

                }

            }

        }

    }

}

```


This code will create a folder on your D drive based on the name of the first image's URL (excluding the file extension), and then it will save all the images fetched from the URLs into that folder. Each subsequent run of the program will create a new folder for each different first image's name encountered.

Post a Comment

Previous Post Next Post