Skip to Content
.NET & XML
book

.NET & XML

by Niel M. Bornstein
November 2003
Intermediate to advanced
476 pages
14h 38m
English
O'Reilly Media, Inc.
Content preview from .NET & XML

Network I/O

Network I/O is generally similar to file I/O, and both Stream and TextReader types are used to access to data from a network connection. The System.Net namespace contains additional classes that are useful in dealing with common network protocols such as HTTP, while the System.Net.Sockets namespace contains generalized classes for dealing with network sockets.

To create a connection to a web server, you will typically use the abstract WebRequest class and its Create( ) and GetResponse( ) methods. Create( ) is a static factory method that returns a new instance of a subclass of WebRequest to handle the URL passed in to Create( ). GetResponse( ) returns a WebResponse object, which provides a method called GetResponseStream( ). The GetResponseStream( ) method returns a Stream object, which you can wrap in a TextReader. As you’ve already seen, you can use a TextReader to read from an I/O stream.

The following code snippet shows a typical sequence for creating a connection to a network data source and displaying its contents to the console device. StreamReader is a concrete implementation of the abstract TextReader base class:

WebRequest request = WebRequest.Create("http://www.oreilly.com/");
WebResponse response = request.GetResponse( );
Stream stream = response.GetResponseStream( );
StreamReader reader = new StreamReader(stream);

// Read a line at a time and write it to the console
while (reader.Peek( ) != -1) {
  Console.WriteLine(reader.ReadLine( ));
}

Tip

A network ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Applied XML Programming for Microsoft® .NET

Applied XML Programming for Microsoft® .NET

Dino Esposito
XML Hacks

XML Hacks

Michael Fitzgerald

Publisher Resources

ISBN: 0596003978Supplemental ContentErrata