0

Im extremely noob in C#. Could you please help me?

I get the following errors:

  • The name 'client' does not exist in the current context
  • Identifier expected
  • Expected class, delegate, enum, interface, or struct

Could you please write me the code that could work properly. I really appreciate your help in advance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using (WebClient client = new WebClient ());

namespace ConsoleApplication3
{
   class Program
   {
      static void Main(string[] args)
      {
         client.DownloadFile("http://yoursite.com/page.html", @"C:\localfile.html");
      }
   }
}
user3203275
  • 195
  • 2
  • 11
  • 2
    `"The name 'client' does not exist in the current context"` means "The name 'client' does not exist in the current context" – musefan Feb 27 '14 at 10:28
  • [please see here](http://stackoverflow.com/questions/307688/how-to-download-a-file-from-a-url-in-c) – musefan Feb 27 '14 at 10:29

1 Answers1

3

You've got this:

using (WebClient client = new WebClient ());

in the list of using directives when you really meant it to be a using statement in the method:

static void Main(string[] args)
{
    using (WebClient client = new WebClient())
    {
       client.DownloadFile("http://yoursite.com/page.html",
                           @"C:\localfile.html");
    }
}

Basically the using keyword has two different meanings in C#:

  • using directives import namespaces and allow type aliases. For example:

    using System; // Imports the System namespace
    using Cons = System.Console; // Creates an alias for the System.Console type
    
  • using statements allow a resource to be easily wrapped in a try/finally block to dispose of the resource at the end of the statement:

    using (SomeResource resource = new SomeResource(...))
    {
        // Use the resource here; it will be disposed of automatically at the
        // end of the block.
    }
    
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194