【问题标题】:How do I download a webpage into a stream in .NET如何将网页下载到 .NET 中的流中
【发布时间】:2010-10-30 02:40:29
【问题描述】:

我知道这应该是一个基本问题,但我遇到了难题。 我正在寻找一个 URL/URI 下载生成的字符串,就好像我打开了一个文件然后将它取出到一个字符串变量中一样。

我一直在使用 IO.Stream 和 Net.httpxxx,但没有设法让元素以正确的方式排列。

我在标准流中打开页面时得到“不支持给定路径的格式”,因为它不在本地文件系统中......我理解的一点,我不明白的一点是......我如何达到以下效果:

Public Function GetWebPageAsString(pURL As String) As String
        Dim lStream As IO.StreamReader = New System.IO.StreamReader(pURL)
        Return lStream.ReadToEnd

End Function

【问题讨论】:

  • 谢谢大家,每个解决方案都有效(最终)我接受的解决方案返回了我正在寻找的东西,而不是我要求的东西,这就是我选择它的原因。 (加上它在 VB 中的 2 行)。下一个 VB 家伙的翻译: Dim client As System.Net.WebClient = New System.Net.WebClient() Dim html As String = client.DownloadString("google.com")
  • 附加说明:我刚刚意识到我的一半问题是我试图获取的 URL 有“-”,在我发出请求之前需要对其进行转义。我可能不需要问我是否在昨晚半夜选择了这个:)

标签: .net vb.net streaming stream


【解决方案1】:

在 C# 中的简短答案看起来像

using(System.Net.WebClient client = new System.Net.WebClient())
{
  string html = client.DownloadString("http://www.google.com");
}

【讨论】:

  • 但这并没有像 OP 要求的那样给你一个 Stream。
  • @Martin:它包括“然后将其放入字符串变量”部分的解决方案
  • 严格来说,这不是我想要的,但这是我想要的:)
【解决方案2】:

WebClient.OpenRead() 可能就是您要找的。​​p>

来自上面链接的 MSDN 页面的示例:

 Dim uriString as String
 uriString = "http://www.google.com"

 Dim myWebClient As New WebClient()

 Console.WriteLine("Accessing {0} ...", uriString)

 Dim myStream As Stream = myWebClient.OpenRead(uriString)

 Console.WriteLine(ControlChars.Cr + "Displaying Data :" + ControlChars.Cr)
 Dim sr As New StreamReader(myStream)
 Console.WriteLine(sr.ReadToEnd())

 myStream.Close()

【讨论】:

  • 谢谢,但我得到 The given path's format is not supported On Dim myStream As Stream = myWebClient.OpenRead(uriString) 网页alllotto.com/Arizona-Pick-3-May-2009-Lottery-Results.php 是网页的问题还是???
  • 与此页面相同stackoverflow.com/questions/929808/… 给出了相同的错误,这是我整晚都在打击的错误。
  • 当我使用此问题的 URL 或“google.com”运行上述示例时,它会按预期工作。您可以将您的完整代码添加到问题中吗?
  • 我已使用示例 URL 更新了代码。这对我有用。
【解决方案3】:

此函数将任何 URI 下载到文件中。您可以轻松地将其调整为将其放入字符串 var:

public static int DownloadFile(String remoteFilename, String localFilename, bool enforceXmlSafe)
{
// Function will return the number of bytes processed
// to the caller. Initialize to 0 here.
int bytesProcessed = 0;

// Assign values to these objects here so that they can
// be referenced in the finally block
Stream remoteStream = null;
Stream localStream = null;
WebResponse response = null;            

// Use a try/catch/finally block as both the WebRequest and Stream
// classes throw exceptions upon error
try
{
    // Create a request for the specified remote file name
    WebRequest request = WebRequest.Create(remoteFilename);
    if (request != null)
    {
        // Send the request to the server and retrieve the
        // WebResponse object 
        response = request.GetResponse();
        if (response != null)
        {
            // Once the WebResponse object has been retrieved,
            // get the stream object associated with the response's data
            remoteStream = response.GetResponseStream();

            // Create the local file
            if (localFilename != null)
                localStream = File.Create(localFilename);
            else
                localStream = new MemoryStream();

            // Allocate a 1k buffer
            byte[] buffer = new byte[1024];
            int bytesRead;

            // Simple do/while loop to read from stream until
            // no bytes are returned
            do
            {
                // Read data (up to 1k) from the stream
                bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

                // Write the data to the local file
                localStream.Write(buffer, 0, bytesRead);

                // Increment total bytes processed
                bytesProcessed += bytesRead;
            } while (bytesRead > 0);
        }
    }
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
finally
{
    // Close the response and streams objects here 
    // to make sure they're closed even if an exception
    // is thrown at some point
    if (response != null) response.Close();
    if (remoteStream != null) remoteStream.Close();
    if (localStream != null) localStream.Close();
}

// Return total bytes processed to caller.
return bytesProcessed;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-14
    • 2015-04-15
    相关资源
    最近更新 更多