間澤東雲
間澤東雲

Reputation: 149

Save image from URL to local hard drive using C#

Im trying to write a console application in order to store a single image from a given path into a new directory as suggested in this article. Despite my program not throwing out any errors the image I want to download just won't show up in my folder. I guess that's because I never told my program where I want the file to be saved? However, I haven't found anything clarifying this particular problem I have right now. I already referred to this and this question, too.


using System;
using System.IO;
using System.Net;

namespace GetImages
{
class Program
{
    static void Main(string[] args)
    {
        string dirPath = @"C:\Users\Stefan\Desktop\Images";

        try
        {
            // Create a new directory
            DirectoryInfo imageDirectory = Directory.CreateDirectory(dirPath);
            Console.WriteLine($"Directory '{Path.GetFileName(dirPath)}' was created successfully in {Directory.GetParent(dirPath)}");

            // Image I'm trying to download from the web
            string filePath = @"http://ilarge.lisimg.com/image/12056736/1080full-jessica-clements.jpg";

            using (WebClient _wc = new WebClient())
            {
                _wc.DownloadFileAsync(new Uri(filePath), Path.GetFileName(filePath));
                _wc.Dispose();
            }

            Console.WriteLine("\nFile successfully saved.");
        }

        catch(Exception e)
        {
            while (e != null)
            {
                Console.WriteLine(e.Message);
                e = e.InnerException;
            }
        }            

        if (System.Diagnostics.Debugger.IsAttached)
        {
            Console.WriteLine("Press any key to continue . . .");
            Console.ReadKey(true);
        }
    }
}

}


Edit: After some time I figured out that the file is saved in "C:\Users\Stefan\Documents\Visual Studio 2017\Projects\GetImages\GetImages\bin\Debug". But how do I get the file to be saved directly to dirPath without moving them from Debug to dirPath separately? My next step would be extending this program to save multiple files at once.

Upvotes: 0

Views: 3284

Answers (2)

Allen King
Allen King

Reputation: 2516

Try this:

using (WebClient _wc = new WebClient())
            {
                _wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath,Path.GetFileName(filePath)));

            }

Upvotes: 0

Alex K.
Alex K.

Reputation: 175936

The second argument of DownloadFileAsync is the save location so combine the path you create and the filename from the URL:

_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath, Path.GetFileName(filePath)));

Upvotes: 2

Related Questions