Saving an image from an URL to a local file in C#

I have the following code which save an image with an URL to a local file.

using (WebClient client = new WebClient())
{
    client.DownloadFile("http://images.craigslist.org/00o0o_kFhPDdTGf2e_600x450.jpg", "c:\\Tmp\test.jpg");
}

But when I run it, I get an exception. It said 'An exception occurred during a WebClient request." When I see that exception in deubgger. It said 'Illegal characters in path.'

I check that url is valid via my browser. So what is causing the problem?

Answers


You should use, @ symbol like this

      using (WebClient client = new WebClient())
        {
            client.DownloadFile(@"http://images.craigslist.org/00o0o_kFhPDdTGf2e_600x450.jpg",                                @"c:\\Tmp\test.jpg");
        }

Your path contains a tab character: \t. Escape the second backslash: "C:\\Tmp\\test.jpg"


"c:\\Tmp\test.jpg"

You forgot to escape the second t.

You should either use @"c:\Tmp\test.jpg" or "c:\\Tmp\\test.jpg"


Just put an @ symbol before the path names.

       using (WebClient client = new WebClient())
        {
            client.DownloadFile(@"http://images.craigslist.org/00o0o_kFhPDdTGf2e_600x450.jpg", @"c:\Tmp\test.jpg");
        }

Your path contains \t which is an illegal path character. Back slash is a reserved character in C#, for characters like tab and line ending, and so must be escaped.

You can either make it a double back slash "C:\\Tmp\\test.jpg", or escape the whole string with an @ character at the beginning @"C:\Tmp\test.jpg"


Try:

"C:\\Tmp\\test.jpg"

for your filename

Treat those like any other string. The first backslash is the escape character, the second is to recognize the backslash


Need Your Help

Debuggin UnitTests in ASP.Net MVC

asp.net-mvc unit-testing debugging

I'm having a problem debugging my unit tests in ASP.Net MVC. Whenever I try and debug a selected test, the breakpoint I set turns in a hollow circle with a warning sign. When I hover over it I ge...

Updating an activity's data from a service

android service lifecycle

I have a service running, and one of its tasks is to regularly fetch data from an external web host. Upon finding new data, the service should update the main activity to show the most recent text....

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.