Compiling new type in PowerShell v2 - Cookie Aware WebClient

夙愿已清 提交于 2019-12-06 00:22:29

问题


I am trying to compile a "cookie aware" version of the WebClient class - but I can't seem to get over some of the hurdles of using the Add-Type cmdlet added in PowerShell v2. Here is the code I am trying to compile:

PS C:\> $def = @"
public class CookieAwareWebClient : System.Net.WebClient
{
  private System.Net.CookieContainer m_container = new System.Net.CookieContainer();
  protected override System.Net.WebRequest GetWebRequest(System.Uri address)
  {
    System.Net.WebRequest request = base.GetWebRequest(address);
    if (request is System.Net.HttpWebRequest)
    {
      (request as System.Net.HttpWebRequest).CookieContainer = m_container;
    }
    return request;
  }
}
"@

PS C:\> Add-Type -TypeDefinition $def

It can't seem to find the CookieContainer type can't be found (though it is fully qualified...) - clearly I am blind on something.

Edit: Updated the sample code to be correct and copy-n-pasteable, thanks!


回答1:


The second reference to CookieContainer with the constructor expression is fully qualified. The first reference, when declaring the field m_container is not. Make both fully qualified so Powershell can find them

private System.Net.CookieContainer m_container = new System.Net.CookieContainer();


来源:https://stackoverflow.com/questions/4261479/compiling-new-type-in-powershell-v2-cookie-aware-webclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!