2009-05-30 7 views
4

Je sais que cela devrait être une question de base, mais je frappe un mur de briques. Je cherche à aller à un URL/URI télécharger la chaîne résultante comme si j'avais ouvert un fichier, puis le sortir dans une variable String.Comment puis-je télécharger une page Web dans un flux dans .NET

J'ai été bourré avec IO.Stream et Net.httpxxx mais je n'ai pas réussi à aligner les éléments de la bonne façon. Je reçois "le format du chemin donné n'est pas supporté" depuis l'ouverture de la page dans le flux standard, parce que ce n'est pas dans le système de fichiers local ... ce que je comprends, le bit que je ne comprends pas est .. Comment puis-je obtenir l'équivalent de:

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

End Function 
+0

Merci tout le monde, chacun solution a fait un travail (éventuellement) celui que j'acceptés Retourné ce que je cherchais plutôt que ce que je demandais, c'est pourquoi je le choisis. (plus ses 2 lignes en VB). Traduction du prochain type VB: Dim client As System.Net.WebClient = Nouveau System.Net.WebClient() Dim html As String = client.DownloadString ("http://www.google.com") –

+0

Note supplémentaire: Je viens juste de réaliser que la moitié de mon problème est que les URL que j'essaie d'obtenir ont '-' qui doit être échappé avant de faire la demande. Je n'aurais probablement pas eu besoin de demander si j'avais choisi cela à minuit hier soir :) –

Répondre

7

La réponse courte, en C#, ressemble à

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

Mais cela ne vous donne pas un flux, comme le PO l'a demandé. – M4N

+0

@Martin: Il comprend une solution pour le "et ensuite le sortir dans une variable String" partie –

+0

Strictement non c'était ce que je demandais, mais c'était ce que je voulais :) –

0

Cette fonction télécharge n'importe quel URI dans un fichier. Vous pouvez facilement l'adapter pour le mettre dans une chaîne 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; 
} 
2

WebClient.OpenRead() pourrait être ce que vous cherchez.

Extrait de la page MSDN liée ci-dessus:

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() 
+0

Merci, mais je reçois Le format du chemin donné n'est pas supporté Sur Dim myStream As Stream = myWebClient.OpenRead (uriString) ligne pour page web http://www.alllotto.com/Arizona-Pick-3-May-2009-Lottery-Results.php Est-ce un problème avec la page web ou ??? –

+0

Même avec cette page même http://stackoverflow.com/questions/929808/how-do-i-download-a-webpage-into-a-stream-in-net donne la même erreur, qui est celle J'ai frappé toute la nuit. –

+0

Lorsque j'exécute l'exemple ci-dessus avec l'URL de cette question ou avec "http://www.google.com", cela fonctionne comme prévu. Pouvez-vous ajouter votre code complet à la question? – M4N