How can I get images from a server and save them locally.

I want to import images from a url and upload it to my server. I have all the url of the images stored on my database (ETSP_GET_PHOTO_URL)

I am very new to this so any help would be nice!

I am doing this in a windows service.

I literally copy/pasted this from a code I wrote, so there might be a little overhead

//downloads an image from the web (if it doesn't exist on file)
public static bool Image (string url, string filename, bool forceDownload) 
{
    //if the file currently doesn't exist (download it) (or if we force it to download again)
    if ((File.Exists(filename) == false) || (forceDownload == true)) 
    {
        if (Directory.Exists(Path.GetDirectoryName(filename)) == false) //if the directory doesn't exist, create it
        {
            Directory.CreateDirectory(Path.GetDirectoryName(filename));
        }

        try //it will try to download
        {
            WebClient client = new WebClient();
            client.DownloadFile(url, filename);
        }
        catch (Exception error)
        {
            return false;
        }
    }

    return true;
}

This piece of code is designed to download the image only if it doesn't exist or if it's told to download it again anyway

Edited 2 Years Ago by JOSheaIV

It would be good to use like this...

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);

or you can try this...

using (SqlConnection con = new SqlConnection(GenericData.DBConnection))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT ImageData FROM Images WHERE Id=@ID", con))
        {
        cmd.Parameters.AddWithValue("@ID", Id);
        SqlDataReader r = cmd.ExecuteReader();
        if (r.Read())
            {
            MemoryStream ms = new MemoryStream((byte[])r["ImageData"]);
            MyImage = Image.FromStream(ms);
            }
        }
    }

Edited 2 Years Ago by Daemon_CC: improve

This article has been dead for over six months. Start a new discussion instead.