如何使用Web代理从Internet读取XML?

时间:2011-01-11 13:46:38

标签: c# xml

这是对此问题的跟进:How to load XML into a DataTable?

我想将互联网上的XML文件读入DataTable。 XML文件位于:http://rates.fxcm.com/RatesXML

如果我这样做:

public DataTable GetCurrentFxPrices(string url)
{
    WebProxy wp = new WebProxy("http://mywebproxy:8080", true);
    wp.Credentials = CredentialCache.DefaultCredentials;
    WebClient wc = new WebClient();
    wc.Proxy = wp;
    MemoryStream ms = new MemoryStream(wc.DownloadData(url));
    DataSet ds = new DataSet("fxPrices");
    ds.ReadXml(ms);
    DataTable dt = ds.Tables["Rate"];
    return dt;
}

工作正常。我正在努力如何在Internet Explorer中使用默认代理集。我不想硬编码代理。如果在Internet Explorer中未指定代理,我也希望代码能够正常工作。

3 个答案:

答案 0 :(得分:2)

您可以使用Console.WriteLine(System.Net.WebProxy.GetDefaultProxy()。Address.AbsoluteUri); ...

答案 1 :(得分:2)

将以下设置添加到app.config / web.config以自动使用系统默认代理:

<system.net>
    <defaultProxy useDefaultCredentials="true"/>
</system.net>

答案 2 :(得分:2)

#region Function to get x-rate via proxy
public string fncProxyGetRate(string countryCode)// use 'GBP' for British Pounds
{
    string rtnTxt = "";
    try
    {
        string url = "http://rss.timegenie.com/forex.xml";
        string proxyUrl = "http://xxx.xxx.x.x:8080/";
        string myXratePath = "/forex/data/code[text()='" + countryCode + "']";

        WebProxy wp = new WebProxy(proxyUrl, true);
        wp.Credentials = CredentialCache.DefaultCredentials;
        WebClient wc = new WebClient();
        wc.Proxy = wp;

        MemoryStream ms = new MemoryStream(wc.DownloadData(url));
        XmlTextReader rdr = new XmlTextReader(ms);

        XmlDocument doc = new XmlDocument();
        doc.Load(rdr);

        rtnTxt = doc.SelectSingleNode(myXratePath).ParentNode.SelectSingleNode("rate").InnerXml;
    }
    catch (Exception ex)
    {
        rtnTxt = ex.Message;
    }
    return rtnTxt;
} 
#endregion