title: Getting an error: The remote server returned an error: (401) Unauthorized. from WebClient class
body: <pre><code>item = 535;
  String URI = "http://localhost:3033/WebFormDesigner.aspx?fm_id=" + item.ToString();
  //String URI = "http://www.google.com";
  WebClient wc = new WebClient();
  Stream s = wc.OpenRead(URI);
  XPathDocument doc = new XPathDocument(s);
  </code></pre>
  
  <p>It doesnt work with:</p>
  
  <pre><code>XPathDocument doc = new XPathDocument(URI);
  </code></pre>
  
  <p>in the above method, using the google URI works, but it doesnt seem to like the URI for localhost at all.  I confirmed that the URI works when put into the browser.  Not quite sure whats going on with it.</p>
  
  <p>The error occurs on the Stream declaration.</p>
  
  <pre><code>The remote server returned an error: (401) Unauthorized.
  </code></pre>
  
  <p>This is an extension of my other post: <a href="https://stackoverflow.com/questions/13033331/how-do-you-get-the-markup-of-a-webpage-in-asp-net-similar-to-phps-get-file-cont">How do you get the markup of a webpage in asp.net similar to php&#39;s get_file_contents</a></p>
  
  <p><strong>Edit: The issue being looked at here, is that there arent permissions to see the page.  The page being visited is a secure page.  What I am trying to do is to give my Request the permissions because the pages are within the same project, but using a WebRequest which assumes it is an outside source.</strong></p>
  
  <p>I was trying to accomplish with a couple different attempted.  Both involved the cookies.</p>
  
  <pre><code>System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URI);
          request.KeepAlive = true;
          request.Credentials = CredentialCache.DefaultCredentials;
          request.CookieContainer = new CookieContainer();
          HttpCookieCollection cookieJar = Request.Cookies;
          //foreach (string cookieString in Request.Cookies)
          for(int i = 0; i &lt; cookieJar.Count; i++)
          {
              System.Web.HttpCookie cookie = cookieJar.Get(i);
              Cookie oC = new Cookie();
              oC.Domain = Request.Url.Host;
              oC.Expires = cookie.Expires;
              oC.Name = cookie.Name;
              oC.Path = cookie.Path;
              oC.Secure = cookie.Secure;
              oC.Value = cookie.Value;
              request.CookieContainer.Add(oC);
          }
          System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
  
          Stream s = response.GetResponseStream();
  </code></pre>
  
  <p>This does some pretty simple stuff, but i guess i am still doing it wrong.  I get the cookies for my current page, and pass them into the cookiecollection for the target page.  After that, i submit the request for a response.  It gives the error above as well.</p>