Csharp/CSharp Tutorial/Network/Uri
Reading Web Pages from a Uri
<source lang="csharp">using System; using System.Net; using System.IO; using System.Text;
class MainClass {
public static void Main(string[] args) { Uri uri = new Uri("http://www.nfex.ru"); WebRequest req = WebRequest.Create(uri); WebResponse resp = req.GetResponse(); Stream stream = resp.GetResponseStream(); StreamReader sr = new StreamReader(stream); string s = sr.ReadToEnd(); Console.WriteLine(s); }
}</source>
<HTML> <HEAD> Java examples (example source code) Organized by topic </title> ... ...
Use a regular expression to extract all fully qualified URIs that refer to HTM files
<source lang="csharp">using System; using System.IO; using System.Net; using System.Text.RegularExpressions; class MainClass {
private static void Main() { string remoteUri = "http://www.nfex.ru"; WebClient client = new WebClient(); Console.WriteLine("Downloading {0}", remoteUri); string str = client.DownloadString(remoteUri); MatchCollection matches = Regex.Matches(str,@"http\S+[^-,;:?]\.htm"); foreach(Match match in matches) { foreach(Group grp in match.Groups) { string file = grp.Value.Substring(grp.Value.LastIndexOf("/")+1); Console.WriteLine(file); } } }
}</source>
Downloading http://www.nfex.ru CatalogJava.htm ^CTerminate batch job (Y/N)? n
Use Uri
<source lang="csharp">using System; using System.Net;
class MainClass {
public static void Main() { Uri sample = new Uri("http://www.yoursite.ru/somefile.txt?SomeQuery"); Console.WriteLine("Host: " + sample.Host); Console.WriteLine("Port: " + sample.Port); Console.WriteLine("Scheme: " + sample.Scheme); Console.WriteLine("Local Path: " + sample.LocalPath); Console.WriteLine("Query: " + sample.Query); Console.WriteLine("Path and query: " + sample.PathAndQuery); }
}</source>
Host: www.yoursite.ru Port: 80 Scheme: http Local Path: /somefile.txt Query: ?SomeQuery Path and query: /somefile.txt?SomeQuery