You are on page 1of 1400

Contents

System.Net
AuthenticationManager
Authenticate
CredentialPolicy
CustomTargetNameDictionary
PreAuthenticate
Register
RegisteredModules
Unregister
AuthenticationSchemes
AuthenticationSchemeSelector
Authorization
Authorization
Complete
ConnectionGroupId
Message
MutuallyAuthenticated
ProtectionRealm
BindIPEndPoint
CipherSuitesCallback
Cookie
Comment
CommentUri
Cookie
Discard
Domain
Equals
Expired
Expires
GetHashCode
HttpOnly
Name
Path
Port
Secure
TimeStamp
ToString
Value
Version
CookieCollection
Add
Clear
Contains
CookieCollection
CopyTo
Count
GetEnumerator
ICollection.CopyTo
ICollection.IsSynchronized
ICollection.SyncRoot
IEnumerable<Cookie>.GetEnumerator
IsReadOnly
IsSynchronized
Item[String]
Remove
SyncRoot
CookieContainer
Add
Capacity
CookieContainer
Count
DefaultCookieLengthLimit
DefaultCookieLimit
DefaultPerDomainCookieLimit
GetCookieHeader
GetCookies
MaxCookieSize
PerDomainCapacity
SetCookies
CookieException
CookieException
GetObjectData
ISerializable.GetObjectData
CredentialCache
Add
CredentialCache
DefaultCredentials
DefaultNetworkCredentials
GetCredential
GetEnumerator
Remove
DecompressionMethods
Dns
BeginGetHostAddresses
BeginGetHostByName
BeginGetHostEntry
BeginResolve
EndGetHostAddresses
EndGetHostByName
EndGetHostEntry
EndResolve
GetHostAddresses
GetHostAddressesAsync
GetHostByAddress
GetHostByName
GetHostEntry
GetHostEntryAsync
GetHostName
Resolve
DnsEndPoint
AddressFamily
DnsEndPoint
Equals
GetHashCode
Host
Port
ToString
DnsPermission
Copy
DnsPermission
FromXml
Intersect
IsSubsetOf
IsUnrestricted
ToXml
Union
DnsPermissionAttribute
CreatePermission
DnsPermissionAttribute
DownloadDataCompletedEventArgs
Result
DownloadDataCompletedEventHandler
DownloadProgressChangedEventArgs
BytesReceived
TotalBytesToReceive
DownloadProgressChangedEventHandler
DownloadStringCompletedEventArgs
Result
DownloadStringCompletedEventHandler
EndPoint
AddressFamily
Create
EndPoint
Serialize
EndpointPermission
Equals
GetHashCode
Hostname
Port
ToString
Transport
FileWebRequest
Abort
BeginGetRequestStream
BeginGetResponse
ConnectionGroupName
ContentLength
ContentType
Credentials
EndGetRequestStream
EndGetResponse
FileWebRequest
GetObjectData
GetRequestStream
GetRequestStreamAsync
GetResponse
GetResponseAsync
Headers
ISerializable.GetObjectData
Method
PreAuthenticate
Proxy
RequestUri
Timeout
UseDefaultCredentials
FileWebResponse
Close
ContentLength
ContentType
Dispose
FileWebResponse
GetObjectData
GetResponseStream
Headers
IDisposable.Dispose
ISerializable.GetObjectData
ResponseUri
SupportsHeaders
FtpStatusCode
FtpWebRequest
Abort
BeginGetRequestStream
BeginGetResponse
ClientCertificates
ConnectionGroupName
ContentLength
ContentOffset
ContentType
Credentials
DefaultCachePolicy
EnableSsl
EndGetRequestStream
EndGetResponse
GetRequestStream
GetResponse
Headers
KeepAlive
Method
PreAuthenticate
Proxy
ReadWriteTimeout
RenameTo
RequestUri
ServicePoint
Timeout
UseBinary
UseDefaultCredentials
UsePassive
FtpWebResponse
BannerMessage
Close
ContentLength
ContentType
ExitMessage
GetResponseStream
Headers
LastModified
ResponseUri
StatusCode
StatusDescription
SupportsHeaders
WelcomeMessage
GlobalProxySelection
GetEmptyWebProxy
GlobalProxySelection
Select
HttpContinueDelegate
HttpListener
Abort
AuthenticationSchemes
AuthenticationSchemeSelectorDelegate
BeginGetContext
Close
DefaultServiceNames
EndGetContext
ExtendedProtectionPolicy
ExtendedProtectionSelectorDelegate
GetContext
GetContextAsync
HttpListener
IDisposable.Dispose
IgnoreWriteExceptions
IsListening
IsSupported
Prefixes
Realm
Start
Stop
TimeoutManager
UnsafeConnectionNtlmAuthentication
HttpListener.ExtendedProtectionSelector
HttpListenerBasicIdentity
HttpListenerBasicIdentity
Password
HttpListenerContext
AcceptWebSocketAsync
Request
Response
User
HttpListenerException
ErrorCode
HttpListenerException
HttpListenerPrefixCollection
Add
Clear
Contains
CopyTo
Count
GetEnumerator
IEnumerable.GetEnumerator
IsReadOnly
IsSynchronized
Remove
HttpListenerRequest
AcceptTypes
BeginGetClientCertificate
ClientCertificateError
ContentEncoding
ContentLength64
ContentType
Cookies
EndGetClientCertificate
GetClientCertificate
GetClientCertificateAsync
HasEntityBody
Headers
HttpMethod
InputStream
IsAuthenticated
IsLocal
IsSecureConnection
IsWebSocketRequest
KeepAlive
LocalEndPoint
ProtocolVersion
QueryString
RawUrl
RemoteEndPoint
RequestTraceIdentifier
ServiceName
TransportContext
Url
UrlReferrer
UserAgent
UserHostAddress
UserHostName
UserLanguages
HttpListenerResponse
Abort
AddHeader
AppendCookie
AppendHeader
Close
ContentEncoding
ContentLength64
ContentType
Cookies
CopyFrom
Headers
IDisposable.Dispose
KeepAlive
OutputStream
ProtocolVersion
Redirect
RedirectLocation
SendChunked
SetCookie
StatusCode
StatusDescription
HttpListenerTimeoutManager
DrainEntityBody
EntityBody
HeaderWait
HttpListenerTimeoutManager
IdleConnection
MinSendBytesPerSecond
RequestQueue
HttpRequestHeader
HttpResponseHeader
HttpStatusCode
HttpVersion
HttpVersion
Unknown
Version10
Version11
Version20
HttpWebRequest
Abort
Accept
AddRange
Address
AllowAutoRedirect
AllowReadStreamBuffering
AllowWriteStreamBuffering
AutomaticDecompression
BeginGetRequestStream
BeginGetResponse
ClientCertificates
Connection
ConnectionGroupName
ContentLength
ContentType
ContinueDelegate
ContinueTimeout
CookieContainer
Credentials
Date
DefaultCachePolicy
DefaultMaximumErrorResponseLength
DefaultMaximumResponseHeadersLength
EndGetRequestStream
EndGetResponse
Expect
GetHashCode
GetObjectData
GetRequestStream
GetResponse
HaveResponse
Headers
Host
HttpWebRequest
IfModifiedSince
ISerializable.GetObjectData
KeepAlive
MaximumAutomaticRedirections
MaximumResponseHeadersLength
MediaType
Method
Pipelined
PreAuthenticate
ProtocolVersion
Proxy
ReadWriteTimeout
Referer
RequestUri
SendChunked
ServerCertificateValidationCallback
ServicePoint
SupportsCookieContainer
Timeout
TransferEncoding
UnsafeAuthenticatedConnectionSharing
UseDefaultCredentials
UserAgent
HttpWebResponse
CharacterSet
Close
ContentEncoding
ContentLength
ContentType
Cookies
Dispose
GetHashCode
GetObjectData
GetResponseHeader
GetResponseStream
Headers
HttpWebResponse
IDisposable.Dispose
ISerializable.GetObjectData
IsMutuallyAuthenticated
LastModified
Method
ProtocolVersion
ResponseUri
Server
StatusCode
StatusDescription
SupportsHeaders
IAuthenticationModule
Authenticate
AuthenticationType
CanPreAuthenticate
PreAuthenticate
ICertificatePolicy
CheckValidationResult
ICredentialPolicy
ShouldSendCredential
ICredentials
GetCredential
ICredentialsByHost
GetCredential
INetworkProgress
ProgressChanged
ProgressCompleted
ProgressFailed
IPAddress
Address
AddressFamily
Any
Broadcast
Equals
GetAddressBytes
GetHashCode
HostToNetworkOrder
IPAddress
IPv6Any
IPv6Loopback
IPv6None
IsIPv4MappedToIPv6
IsIPv6LinkLocal
IsIPv6Multicast
IsIPv6SiteLocal
IsIPv6Teredo
IsLoopback
Loopback
MapToIPv4
MapToIPv6
NetworkToHostOrder
None
Parse
ScopeId
ToString
TryFormat
TryParse
TryWriteBytes
IPEndPoint
Address
Address
AddressFamily
Create
Equals
GetHashCode
IPEndPoint
MaxPort
MinPort
Parse
Port
Serialize
ToString
TryParse
IPEndPointCollection
InsertItem
IPEndPointCollection
SetItem
IPHostEntry
AddressList
Aliases
HostName
IPHostEntry
IUnsafeWebRequestCreate
Create
IWebProxy
Credentials
GetProxy
IsBypassed
IWebProxyScript
Close
Load
Run
IWebRequestCreate
Create
NetworkAccess
NetworkCredential
Domain
GetCredential
NetworkCredential
Password
SecurePassword
UserName
NetworkProgressChangedEventArgs
NetworkProgressChangedEventArgs
ProcessedBytes
TotalBytes
OpenReadCompletedEventArgs
Result
OpenReadCompletedEventHandler
OpenWriteCompletedEventArgs
Result
OpenWriteCompletedEventHandler
ProtocolViolationException
GetObjectData
ISerializable.GetObjectData
ProtocolViolationException
SecurityProtocolType
ServicePoint
Address
BindIPEndPointDelegate
Certificate
ClientCertificate
CloseConnectionGroup
ConnectionLeaseTimeout
ConnectionLimit
ConnectionName
CurrentConnections
Expect100Continue
GetHashCode
IdleSince
MaxIdleTime
ProtocolVersion
ReceiveBufferSize
SetTcpKeepAlive
SupportsPipelining
UseNagleAlgorithm
ServicePointManager
CertificatePolicy
CheckCertificateRevocationList
ClientCipherSuitesCallback
DefaultConnectionLimit
DefaultNonPersistentConnectionLimit
DefaultPersistentConnectionLimit
DnsRefreshTimeout
EnableDnsRoundRobin
EncryptionPolicy
Expect100Continue
FindServicePoint
MaxServicePointIdleTime
MaxServicePoints
ReusePort
SecurityProtocol
ServerCertificateValidationCallback
ServerCipherSuitesCallback
SetTcpKeepAlive
UseNagleAlgorithm
SocketAddress
Equals
Equals
Family
GetHashCode
Item[Int32]
Size
SocketAddress
ToString
SocketPermission
AcceptList
AddPermission
AllPorts
ConnectList
Copy
FromXml
Intersect
IsSubsetOf
IsUnrestricted
SocketPermission
ToXml
Union
SocketPermissionAttribute
Access
CreatePermission
Host
Port
SocketPermissionAttribute
Transport
TransportContext
GetChannelBinding
GetTlsTokenBindings
TransportContext
TransportType
UiSynchronizationContext
Current
ManagedUiThreadId
UploadDataCompletedEventArgs
Result
UploadDataCompletedEventHandler
UploadFileCompletedEventArgs
Result
UploadFileCompletedEventHandler
UploadProgressChangedEventArgs
BytesReceived
BytesSent
TotalBytesToReceive
TotalBytesToSend
UploadProgressChangedEventHandler
UploadStringCompletedEventArgs
Result
UploadStringCompletedEventHandler
UploadValuesCompletedEventArgs
Result
UploadValuesCompletedEventHandler
WebClient
AllowReadStreamBuffering
AllowWriteStreamBuffering
BaseAddress
CachePolicy
CancelAsync
Credentials
DownloadData
DownloadDataAsync
DownloadDataCompleted
DownloadDataTaskAsync
DownloadFile
DownloadFileAsync
DownloadFileCompleted
DownloadFileTaskAsync
DownloadProgressChanged
DownloadString
DownloadStringAsync
DownloadStringCompleted
DownloadStringTaskAsync
Encoding
GetWebRequest
GetWebResponse
Headers
IsBusy
OnDownloadDataCompleted
OnDownloadFileCompleted
OnDownloadProgressChanged
OnDownloadStringCompleted
OnOpenReadCompleted
OnOpenWriteCompleted
OnUploadDataCompleted
OnUploadFileCompleted
OnUploadProgressChanged
OnUploadStringCompleted
OnUploadValuesCompleted
OnWriteStreamClosed
OpenRead
OpenReadAsync
OpenReadCompleted
OpenReadTaskAsync
OpenWrite
OpenWriteAsync
OpenWriteCompleted
OpenWriteTaskAsync
Proxy
QueryString
ResponseHeaders
UploadData
UploadDataAsync
UploadDataCompleted
UploadDataTaskAsync
UploadFile
UploadFileAsync
UploadFileCompleted
UploadFileTaskAsync
UploadProgressChanged
UploadString
UploadStringAsync
UploadStringCompleted
UploadStringTaskAsync
UploadValues
UploadValuesAsync
UploadValuesCompleted
UploadValuesTaskAsync
UseDefaultCredentials
WebClient
WriteStreamClosed
WebException
GetObjectData
ISerializable.GetObjectData
Response
Status
WebException
WebExceptionStatus
WebHeaderCollection
Add
Add
AddWithoutValidate
AllKeys
Clear
Count
Get
GetEnumerator
GetKey
GetObjectData
GetValues
IEnumerable.GetEnumerator
ISerializable.GetObjectData
IsRestricted
Item[String]
Keys
OnDeserialization
Remove
Set
ToByteArray
ToString
WebHeaderCollection
WebPermission
AcceptList
AddPermission
ConnectList
Copy
FromXml
Intersect
IsSubsetOf
IsUnrestricted
ToXml
Union
WebPermission
WebPermissionAttribute
Accept
AcceptPattern
Connect
ConnectPattern
CreatePermission
WebPermissionAttribute
WebProxy
Address
BypassArrayList
BypassList
BypassProxyOnLocal
CreateDefaultProxy
Credentials
GetDefaultProxy
GetObjectData
GetProxy
IsBypassed
ISerializable.GetObjectData
UseDefaultCredentials
WebProxy
WebRequest
Abort
AuthenticationLevel
BeginGetRequestStream
BeginGetResponse
CachePolicy
ConnectionGroupName
ContentLength
ContentType
Create
CreateDefault
CreateHttp
CreatorInstance
Credentials
DefaultCachePolicy
DefaultWebProxy
EndGetRequestStream
EndGetResponse
GetObjectData
GetRequestStream
GetRequestStreamAsync
GetResponse
GetResponseAsync
GetSystemWebProxy
Headers
ImpersonationLevel
ISerializable.GetObjectData
Method
PreAuthenticate
Proxy
RegisterPortableWebRequestCreator
RegisterPrefix
RequestUri
Timeout
UseDefaultCredentials
WebRequest
WebRequestMethods
WebRequestMethods.File
DownloadFile
UploadFile
WebRequestMethods.Ftp
AppendFile
DeleteFile
DownloadFile
GetDateTimestamp
GetFileSize
ListDirectory
ListDirectoryDetails
MakeDirectory
PrintWorkingDirectory
RemoveDirectory
Rename
UploadFile
UploadFileWithUniqueName
WebRequestMethods.Http
Connect
Get
Head
MkCol
Post
Put
WebResponse
Close
ContentLength
ContentType
Dispose
GetObjectData
GetResponseStream
Headers
IDisposable.Dispose
ISerializable.GetObjectData
IsFromCache
IsMutuallyAuthenticated
ResponseUri
SupportsHeaders
WebResponse
WebUtility
HtmlDecode
HtmlEncode
UrlDecode
UrlDecodeToBytes
UrlEncode
UrlEncodeToBytes
WriteStreamClosedEventArgs
Error
WriteStreamClosedEventArgs
WriteStreamClosedEventHandler
System.Net Namespace
The System.Net namespace provides a simple programming interface for many of the protocols used on networks
today. The WebRequest and WebResponse classes form the basis of what are called pluggable protocols, an
implementation of network services that enables you to develop applications that use Internet resources without
worrying about the specific details of the individual protocols.
Classes in the System.Net namespace can be used to develop Windows Store apps or desktop apps. When used in a
Windows Store app, classes in the System.Net namespace are affected by network isolation feature, part of the
application security model used by the Windows Developer Preview. The appropriate network capabilities must be
enabled in the app manifest for a Windows Store app for the system to allow network access by a Windows Store app.
For more information, see the Network Isolation for Windows Store Apps.

Classes
AuthenticationManager
Manages the authentication modules called during the client
authentication process.

Authorization
Contains an authentication message for an Internet server.

Cookie
Provides a set of properties and methods that are used to
manage cookies. This class cannot be inherited.

CookieCollection
Provides a collection container for instances of the Cookie
class.

CookieContainer
Provides a container for a collection of CookieCollection
objects.

CookieException
The exception that is thrown when an error is made adding a
Cookie to a CookieContainer.

CredentialCache
Provides storage for multiple credentials.

Dns
Provides simple domain name resolution functionality.

DnsEndPoint
Represents a network endpoint as a host name or a string
representation of an IP address and a port number.

DnsPermission
Controls rights to access Domain Name System (DNS) servers
on the network.
DnsPermissionAttribute
Specifies permission to request information from Domain
Name Servers.

DownloadDataCompletedEventArgs
Provides data for the DownloadDataCompleted event.

DownloadProgressChangedEventArgs
Provides data for the DownloadProgressChanged event of a
WebClient.

DownloadStringCompletedEventArgs
Provides data for the DownloadStringCompleted event.

EndPoint
Identifies a network address. This is an abstract class.

EndpointPermission
Defines an endpoint that is authorized by a SocketPermission
instance.

FileWebRequest
Provides a file system implementation of the WebRequest
class.

FileWebResponse
Provides a file system implementation of the WebResponse
class.

FtpWebRequest
Implements a File Transfer Protocol (FTP) client.

FtpWebResponse
Encapsulates a File Transfer Protocol (FTP) server's response to
a request.

GlobalProxySelection
Contains a global default proxy instance for all HTTP requests.

HttpListener
Provides a simple, programmatically controlled HTTP protocol
listener. This class cannot be inherited.

HttpListenerBasicIdentity
Holds the user name and password from a basic
authentication request.

HttpListenerContext
Provides access to the request and response objects used by
the HttpListener class. This class cannot be inherited.
HttpListenerException
The exception that is thrown when an error occurs processing
an HTTP request.

HttpListenerPrefixCollection
Represents the collection used to store Uniform Resource
Identifier (URI) prefixes for HttpListener objects.

HttpListenerRequest
Describes an incoming HTTP request to an HttpListener
object. This class cannot be inherited.

HttpListenerResponse
Represents a response to a request being handled by an
HttpListener object.

HttpListenerTimeoutManager
The timeout manager to use for an HttpListener object.

HttpVersion
Defines the HTTP version numbers that are supported by the
HttpWebRequest and HttpWebResponse classes.

HttpWebRequest
Provides an HTTP-specific implementation of the WebRequest
class.

HttpWebResponse
Provides an HTTP-specific implementation of the
WebResponse class.

IPAddress
Provides an Internet Protocol (IP) address.

IPEndPoint
Represents a network endpoint as an IP address and a port
number.

IPEndPointCollection
Represents a collection used to store network endpoints as
IPEndPoint objects.

IPHostEntry
Provides a container class for Internet host address
information.

NetworkCredential
Provides credentials for password-based authentication
schemes such as basic, digest, NTLM, and Kerberos
authentication.
NetworkProgressChangedEventArgs
Provides data for the network progress changed event.

OpenReadCompletedEventArgs
Provides data for the OpenReadCompleted event.

OpenWriteCompletedEventArgs
Provides data for the OpenWriteCompleted event.

ProtocolViolationException
The exception that is thrown when an error is made while
using a network protocol.

ServicePoint
Provides connection management for HTTP connections.

ServicePointManager
Manages the collection of ServicePoint objects.

SocketAddress
Stores serialized information from EndPoint derived classes.

SocketPermission
Controls rights to make or accept connections on a transport
address.

SocketPermissionAttribute
Specifies security actions to control Socket connections. This
class cannot be inherited.

TransportContext
The TransportContext class provides additional context about
the underlying transport layer.

UiSynchronizationContext
Provides the synchronization context for the managed UI used
in synchronization models.

UploadDataCompletedEventArgs
Provides data for the UploadDataCompleted event.

UploadFileCompletedEventArgs
Provides data for the UploadFileCompleted event.

UploadProgressChangedEventArgs
Provides data for the UploadProgressChanged event of a
WebClient.

UploadStringCompletedEventArgs
Provides data for the UploadStringCompleted event.
UploadValuesCompletedEventArgs
Provides data for the UploadValuesCompleted event.

WebClient
Provides common methods for sending data to and receiving
data from a resource identified by a URI.

WebException
The exception that is thrown when an error occurs while
accessing the network through a pluggable protocol.

WebHeaderCollection
Contains protocol headers associated with a request or
response.

WebPermission
Controls rights to access HTTP Internet resources.

WebPermissionAttribute
Specifies permission to access Internet resources. This class
cannot be inherited.

WebProxy
Contains HTTP proxy settings for the WebRequest class.

WebRequest
Makes a request to a Uniform Resource Identifier (URI). This is
an abstract class.

WebRequestMethods
Container class for WebRequestMethods.Ftp,
WebRequestMethods.File, and WebRequestMethods.Http
classes. This class cannot be inherited

WebRequestMethods.File
Represents the types of file protocol methods that can be
used with a FILE request. This class cannot be inherited.

WebRequestMethods.Ftp
Represents the types of FTP protocol methods that can be
used with an FTP request. This class cannot be inherited.

WebRequestMethods.Http
Represents the types of HTTP protocol methods that can be
used with an HTTP request.

WebResponse
Provides a response from a Uniform Resource Identifier (URI).
This is an abstract class.
WebUtility
Provides methods for encoding and decoding URLs when
processing Web requests.

WriteStreamClosedEventArgs
Provides data for the WriteStreamClosed event.

Interfaces
IAuthenticationModule
Provides the base authentication interface for Web client
authentication modules.

ICertificatePolicy
Validates a server certificate.

ICredentialPolicy
Defines the credential policy to be used for resource requests
that are made using WebRequest and its derived classes.

ICredentials
Provides the base authentication interface for retrieving
credentials for Web client authentication.

ICredentialsByHost
Provides the interface for retrieving credentials for a host,
port, and authentication type.

INetworkProgress
Provides information on network progress in sending data
over the network.

IUnsafeWebRequestCreate
Creates an unsafe WebRequest to a Uniform Resource
Identifier (URI).

IWebProxy
Provides the base interface for implementation of proxy access
for the WebRequest class.

IWebProxyScript
Provides the base interface to load and execute scripts for
automatic proxy detection.

IWebRequestCreate
Provides the base interface for creating WebRequest instances.

Enums
AuthenticationSchemes
Specifies protocols for authentication.

DecompressionMethods
Represents the file compression and decompression encoding
format to be used to compress the data received in response
to an HttpWebRequest.

FtpStatusCode
Specifies the status codes returned for a File Transfer Protocol
(FTP) operation.

HttpRequestHeader
The HTTP headers that may be specified in a client request.

HttpResponseHeader
The HTTP headers that can be specified in a server response.

HttpStatusCode
Contains the values of status codes defined for HTTP.

NetworkAccess
Specifies network access permissions.

SecurityProtocolType
Specifies the security protocols that are supported by the
Schannel security package.

TransportType
Defines transport types for the SocketPermission and Socket
classes.

WebExceptionStatus
Defines status codes for the WebException class.

Delegates
AuthenticationSchemeSelector
Selects the authentication scheme for an HttpListener
instance.

BindIPEndPoint
Represents the method that specifies a local Internet Protocol
address and port number for a ServicePoint.

CipherSuitesCallback

DownloadDataCompletedEventHandler
Represents the method that will handle the
DownloadDataCompleted event of a WebClient.
DownloadProgressChangedEventHandler
Represents the method that will handle the
DownloadProgressChanged event of a WebClient.

DownloadStringCompletedEventHandler
Represents the method that will handle the
DownloadStringCompleted event of a WebClient.

HttpContinueDelegate
Represents the method that notifies callers when a continue
response is received by the client.

HttpListener.ExtendedProtectionSelector
A delegate called to determine the ExtendedProtectionPolicy
to use for each HttpListener request.

OpenReadCompletedEventHandler
Represents the method that will handle the
OpenReadCompleted event of a WebClient.

OpenWriteCompletedEventHandler
Represents the method that will handle the
OpenWriteCompleted event of a WebClient.

UploadDataCompletedEventHandler
Represents the method that will handle the
UploadDataCompleted event of a WebClient.

UploadFileCompletedEventHandler
Represents the method that will handle the
UploadFileCompleted event of a WebClient.

UploadProgressChangedEventHandler
Represents the method that will handle the
UploadProgressChanged event of a WebClient.

UploadStringCompletedEventHandler
Represents the method that will handle the
UploadStringCompleted event of a WebClient.

UploadValuesCompletedEventHandler
Represents the method that will handle the
UploadValuesCompleted event of a WebClient.

WriteStreamClosedEventHandler
Represents the method that will handle the
WriteStreamClosed event of a WebClient.
AuthenticationManager AuthenticationManager Class
Manages the authentication modules called during the client authentication process.

D eclaration
public class AuthenticationManager
type AuthenticationManager = class

I nheritance H ierarchy
Object Object

Remarks
AuthenticationManager is a static class that manages the authentication modules that an application uses. When a
request is made to protected resources, the AuthenticationManager calls the Authenticate method to get an
Authorization instance to use in subsequent requests.
The AuthenticationManager queries each registered authentication module by calling the
IAuthenticationModule.Authenticate method for each module. The first authentication module to return an
Authorization instance is used to authenticate the request.
Modules that provide the basic, digest, negotiate, NTLM, and Kerberos authentication types are registered with the
AuthenticationManager by default. Additional authentication modules that implement the IAuthenticationModule
interface can be added using the Register method. Authentication modules are called in the order in which they were
added to the list.
Note

The Kerberos and negotiate authentication type is not supported on Windows 95/98 or Windows NT 4.0.

Properties
CredentialPolicy
CredentialPolicy

Gets or sets the credential policy to be used for resource requests made using the HttpWebRequest class.

CustomTargetNameDictionary
CustomTargetNameDictionary

Gets the dictionary that contains Service Principal Names (SPNs) that are used to identify hosts during Kerberos
authentication for requests made using WebRequest and its derived classes.

RegisteredModules
RegisteredModules

Gets a list of authentication modules that are registered with the authentication manager.

Methods
Authenticate(String, WebRequest, ICredentials)
Authenticate(String, WebRequest, ICredentials)

Calls each registered authentication module to find the first module that can respond to the authentication
request.

PreAuthenticate(WebRequest, ICredentials)
PreAuthenticate(WebRequest, ICredentials)

Preauthenticates a request.

Register(IAuthenticationModule)
Register(IAuthenticationModule)

Registers an authentication module with the authentication manager.

Unregister(IAuthenticationModule)
Unregister(IAuthenticationModule)

Removes the specified authentication module from the list of registered modules.

Unregister(String)
Unregister(String)

Removes authentication modules with the specified authentication scheme from the list of registered modules.

See Also
AuthenticationManager.Authenticate Authentication
Manager.Authenticate
I n this Article
Calls each registered authentication module to find the first module that can respond to the authentication request.

public static System.Net.Authorization Authenticate (string challenge, System.Net.WebRequest


request, System.Net.ICredentials credentials);
static member Authenticate : string * System.Net.WebRequest * System.Net.ICredentials ->
System.Net.Authorization

Parameters
challenge String String
The challenge returned by the Internet resource.
request WebRequest WebRequest
The WebRequest that initiated the authentication challenge.
credentials ICredentials ICredentials
The ICredentials associated with this request.
Returns
Authorization Authorization
An instance of the Authorization class containing the result of the authorization attempt. If there is no authentication
module to respond to the challenge, this method returns null .

Exceptions
ArgumentNullException ArgumentNullException
challenge is null .
-or-
request is null .
-or-
credentials is null .

Remarks
The Authenticate method calls the IAuthenticationModule.Authenticate method on each registered authentication
module until one of the module responds with an Authorization instance.
The first Authorization instance returned is used to authenticate the request. If no authentication module can
authenticate the request, the Authenticate method returns null .
Authentication modules are called in the order in which they are registered with the AuthenticationManager.
AuthenticationManager.CredentialPolicy Authentication
Manager.CredentialPolicy
I n this Article
Gets or sets the credential policy to be used for resource requests made using the HttpWebRequest class.

public static System.Net.ICredentialPolicy CredentialPolicy { get; set; }


member this.CredentialPolicy : System.Net.ICredentialPolicy with get, set

Returns
ICredentialPolicy ICredentialPolicy
An object that implements the ICredentialPolicy interface that determines whether credentials are sent with requests.
The default value is null .

Examples
The following code example demonstrates setting the credential policy.
public static void UseIntranetCredentialPolicy()
{
IntranetZoneCredentialPolicy policy = new IntranetZoneCredentialPolicy();
AuthenticationManager.CredentialPolicy = policy;
}

Remarks
The credential policy determines whether to send credentials when sending a request for a network resource, such as
the content of a Web page. If credentials are sent, servers that require client authentication can attempt to authenticate
the client when the request is received instead of sending a response indicating that the client's credentials are
required. While this saves a round trip to the server, this must be balanced against the security risk inherent in sending
credentials across the network. When the destination server does not require client authentication it is best to not send
credentials.
The credential policy will be called only for requests that specify credentials or use a WebProxy object that specifies
credentials.
AuthenticationManager.CustomTargetNameDictionary
AuthenticationManager.CustomTargetNameDictionary
I n this Article
Gets the dictionary that contains Service Principal Names (SPNs) that are used to identify hosts during Kerberos
authentication for requests made using WebRequest and its derived classes.
public static System.Collections.Specialized.StringDictionary CustomTargetNameDictionary { get; }
member this.CustomTargetNameDictionary : System.Collections.Specialized.StringDictionary

Returns
StringDictionary StringDictionary
A writable StringDictionary that contains the SPN values for keys composed of host information.

Examples
The following code example demonstrates displaying the contents of the CustomTargetNameDictionary.
public static void RequestResource(Uri resource)
{
// Set policy to send credentials when using HTTPS and basic authentication.

// Create a new HttpWebRequest object for the specified resource.


WebRequest request=(WebRequest) WebRequest.Create(resource);
// Supply client credentials for basic authentication.
request.UseDefaultCredentials = true;
request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequired;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// Determine mutual authentication was used.
Console.WriteLine("Is mutually authenticated? {0}", response.IsMutuallyAuthenticated);

System.Collections.Specialized.StringDictionary spnDictionary =
AuthenticationManager.CustomTargetNameDictionary;
foreach (System.Collections.DictionaryEntry e in spnDictionary)
{
Console.WriteLine("Key: {0} - {1}", e.Key as string, e.Value as string);
}
// Read and display the response.
System.IO.Stream streamResponse = response.GetResponseStream();
System.IO.StreamReader streamRead = new System.IO.StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream objects.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse.
response.Close();
}

/*

The output from this example will differ based on the requested resource
and whether mutual authentication was successful. For the purpose of illustration,
a sample of the output is shown here:

Is mutually authenticated? True


Key: http://server1.someDomain.contoso.com - HTTP/server1.someDomain.contoso.com

<html>
...
</html>

*/

Remarks
An SPN is a name by which a client uniquely identifies an instance of a service or application on a server for purposes
of mutual authentication. Mutual authentication is requested by default, and you can require it by setting
WebRequest.AuthenticationLevel to MutualAuthRequired in your request.
When a WebRequest requires mutual authentication, the SPN for the destination must be supplied by the client. If you
know the SPN, you can add it to the CustomTargetNameDictionary before sending the request. If you have not added
SPN information to this dictionary, the AuthenticationManager uses the RequestUri method to compose the most
likely SPN; however, this is a computed value and might be incorrect. If mutual authentication is attempted and fails,
you can check the dictionary to determine the computed SPN. No SPN is entered into the dictionary if the
authentication protocol does not support mutual authentication.
To add an SPN value to this dictionary, use the AbsoluteUri of the RequestUri as the key. Internally, the key is truncated
to include the Scheme, Host, and the Port if it is not the default port.
Note

Accessing the methods and properties of the CustomTargetNameDictionary requires unrestricted WebPermission.
Note

When Kerberos authentication is performed through a proxy, both the proxy and the ultimate host name need to be
resolved to an SPN. The proxy name resolution is protected by a timeout. Resolution of the ultimate host name to a
SPN requires a DNS lookup, and there is no timeout associated directly with this operation. Therefore synchronous
operations may take longer to timeout. To overcome this, add the ultimate host's URI prefix to the SPN cache prior to
making requests to it.
Version 3.5 SP1 now defaults to specifying the host name used in the request URL in the SPN in the NTLM (NT LAN
Manager) authentication exchange when the CustomTargetNameDictionary property is not set. The host name used in
the request URL may be different from the Host header specified in the System.Net.HttpRequestHeader in the client
request. The host name used in the request URL may be different from the actual host name of the server, the machine
name of the server, the computer's IP address, or the loopback address. In these cases, Windows will fail the
authentication request. To address the issue, you may need to notify Windows that the host name used in the request
URL in the client request ("contoso", for example) is actually an alternate name for the local computer.
See Changes to NTLM authentication for HTTPWebRequest in Version 3.5 SP1
Also
AuthenticationManager.PreAuthenticate Authentication
Manager.PreAuthenticate
I n this Article
Preauthenticates a request.

public static System.Net.Authorization PreAuthenticate (System.Net.WebRequest request,


System.Net.ICredentials credentials);
static member PreAuthenticate : System.Net.WebRequest * System.Net.ICredentials ->
System.Net.Authorization

Parameters
request WebRequest WebRequest
A WebRequest to an Internet resource.
credentials ICredentials ICredentials
The ICredentials associated with the request.
Returns
Authorization Authorization
An instance of the Authorization class if the request can be preauthenticated; otherwise, null . If credentials is null ,
this method returns null .
Exceptions
ArgumentNullException ArgumentNullException
request is null .

Remarks
If the authentication module can preauthenticate the request, the PreAuthenticate method returns an Authentication
instance and sends the authorization information to the server preemptively instead of waiting for the resource to issue
a challenge. This behavior is outlined in section 3.3 of RFC 2617 (HTTP Authentication: Basic and Digest Access
Authentication). Authentication modules that support preauthentication allow clients to improve server efficiency by
avoiding extra round trips caused by authentication challenges.
Authorization modules that can preauthenticate requests set the IAuthenticationModule.CanPreAuthenticate property
to true .
AuthenticationManager.Register AuthenticationManager.
Register
I n this Article
Registers an authentication module with the authentication manager.

public static void Register (System.Net.IAuthenticationModule authenticationModule);


static member Register : System.Net.IAuthenticationModule -> unit

Parameters
authenticationModule IAuthenticationModule IAuthenticationModule
The IAuthenticationModule to register with the authentication manager.
Exceptions
ArgumentNullException ArgumentNullException
authenticationModule is null .

Examples
The following example registers an authentication module with the authentication manager. For a complete example,
refer to the AuthenticationManager class.
// This is the program entry point. It allows the user to enter
// her credentials and the Internet resource (Web page) to access.
// It also unregisters the standard and registers the customized basic
// authentication.
public static void Main(string[] args)
{

if (args.Length < 3)
showusage();
else
{

// Read the user's credentials.


uri = args[0];
username = args[1];
password = args[2];

if (args.Length == 3)
domain = string.Empty;
else
// If the domain exists, store it. Usually the domain name
// is by default the name of the server hosting the Internet
// resource.
domain = args[3];

// Unregister the standard Basic authentication module.


AuthenticationManager.Unregister("Basic");

// Instantiate the custom Basic authentication module.


CustomBasic customBasicModule = new CustomBasic();

// Register the custom Basic authentication module.


AuthenticationManager.Register(customBasicModule);

// Display registered Authorization modules.


displayRegisteredModules();

// Read the specified page and display it on the console.


getPage(uri);
}
return;
}

Remarks
The Register method adds authentication modules to the end of the list of modules called by the Authenticate method.
Authentication modules are called in the order in which they were added to the list. If a module with the same
AuthenticationType is already registered, this method removes the registered module and adds
authenticationModule to the end of the list.
AuthenticationManager.RegisteredModules
AuthenticationManager.RegisteredModules
I n this Article
Gets a list of authentication modules that are registered with the authentication manager.

public static System.Collections.IEnumerator RegisteredModules { get; }


member this.RegisteredModules : System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
An IEnumerator that enables the registered authentication modules to be read.

Examples
The following example uses the RegisteredModules property to get a list of authentication modules that are registered
with the authentication manager. For a complete example, refer to the AuthenticationManager class.
// Display registered authentication modules.
private static void displayRegisteredModules()
{
// The AuthenticationManager calls all authentication modules sequentially
// until one of them responds with an authorization instance. Show
// the current registered modules.
IEnumerator registeredModules = AuthenticationManager.RegisteredModules;
Console.WriteLine("\r
The following authentication modules are now registered with the system:");
while(registeredModules.MoveNext())
{
Console.WriteLine("\r
Module : {0}",registeredModules.Current);
IAuthenticationModule currentAuthenticationModule =
(IAuthenticationModule)registeredModules.Current;
Console.WriteLine(" CanPreAuthenticate :
{0}",currentAuthenticationModule.CanPreAuthenticate);
}
}

Remarks
The RegisteredModules property provides an IEnumerator instance that enables the list of registered authentication
modules to be read. The Register method adds modules to the list, and the Unregister method removes modules from
it.
AuthenticationManager.Unregister Authentication
Manager.Unregister
I n this Article

Overloads
Unregister(IAuthenticationModule) Unregister(IAuthentication
Module) Removes the specified authentication module from the list of
registered modules.

Unregister(String) Unregister(String)
Removes authentication modules with the specified
authentication scheme from the list of registered modules.

Unregister(IAuthenticationModule)
Unregister(IAuthenticationModule)
Removes the specified authentication module from the list of registered modules.

public static void Unregister (System.Net.IAuthenticationModule authenticationModule);


static member Unregister : System.Net.IAuthenticationModule -> unit

Parameters
authenticationModule IAuthenticationModule IAuthenticationModule
The IAuthenticationModule to remove from the list of registered modules.
Exceptions
ArgumentNullException ArgumentNullException
authenticationModule is null .
InvalidOperationException InvalidOperationException
The specified IAuthenticationModule is not registered.
Examples
The following example uses the Unregister method to remove the specified authentication module from the list of
registered modules. For a complete example, refer to the AuthenticationManager class.
// This is the program entry point. It allows the user to enter
// her credentials and the Internet resource (Web page) to access.
// It also unregisters the standard and registers the customized basic
// authentication.
public static void Main(string[] args)
{

if (args.Length < 3)
showusage();
else
{

// Read the user's credentials.


uri = args[0];
username = args[1];
password = args[2];

if (args.Length == 3)
domain = string.Empty;
else
// If the domain exists, store it. Usually the domain name
// is by default the name of the server hosting the Internet
// resource.
domain = args[3];

// Unregister the standard Basic authentication module.


AuthenticationManager.Unregister("Basic");

// Instantiate the custom Basic authentication module.


CustomBasic customBasicModule = new CustomBasic();

// Register the custom Basic authentication module.


AuthenticationManager.Register(customBasicModule);

// Display registered Authorization modules.


displayRegisteredModules();

// Read the specified page and display it on the console.


getPage(uri);
}
return;
}

Remarks
The Unregister method removes the specified authentication module from the list of authentication modules called by
the Authenticate method. The module must have been added to the list using the Register method before it can be
removed from the list.

Unregister(String) Unregister(String)
Removes authentication modules with the specified authentication scheme from the list of registered modules.

public static void Unregister (string authenticationScheme);


static member Unregister : string -> unit

Parameters
authenticationScheme String String
The authentication scheme of the module to remove.
Exceptions
ArgumentNullException ArgumentNullException
authenticationScheme is null .

InvalidOperationException InvalidOperationException
A module for this authentication scheme is not registered.
Examples
The following example uses the Unregister method to remove an authentication module with the specified
authentication scheme from the list of registered modules.

IEnumerator registeredModules = AuthenticationManager.RegisteredModules;


// Display all the modules that are already registered with the system.
DisplayAllModules();
registeredModules.Reset();
registeredModules.MoveNext();
// Get the first Authentication module registered with the system.
IAuthenticationModule authenticationModule1 = (IAuthenticationModule)registeredModules.Current;
// Call the UnRegister() method to unregister the first authentication module from the system.
String authenticationScheme = authenticationModule1.AuthenticationType;
AuthenticationManager.Unregister(authenticationScheme);
Console.WriteLine("
Successfully unregistered '{0}",authenticationModule1+"'.");
// Display all modules to see that the module was unregistered.
DisplayAllModules();

Remarks
The Unregister method removes the authentication module with the specified authentication scheme from the list of
authentication modules called by the Authenticate method. The module must have been added to the list using the
Register method before it can be removed from the list.
AuthenticationSchemes AuthenticationSchemes Enum
Specifies protocols for authentication.

D eclaration
[System.Flags]
public enum AuthenticationSchemes
type AuthenticationSchemes =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
This enumeration is used to specify the method used to authenticate client requests being processed by HttpListener
objects.
Im p o rt a nt

Basic authentication requires the exchange of a password and should therefore be avoided except in the case of secure,
encrypted connections.
For additional information on basic and digest authentication, see RFC2617 - HTTP Authentication: Basic and Digest
Authentication. This document is available at https://www.rfc-editor.org.

Fields
Anonymous Anonymous Specifies anonymous authentication.

Basic Basic Specifies basic authentication.

Digest Digest Specifies digest authentication.

IntegratedWindowsAuthentication Specifies Windows authentication.


IntegratedWindowsAuthentication

Negotiate Negotiate Negotiates with the client to determine the authentication scheme. If both client
and server support Kerberos, it is used; otherwise, NTLM is used.

None None No authentication is allowed. A client requesting an HttpListener object with this
flag set will always receive a 403 Forbidden status. Use this flag when a resource
should never be served to a client.
Ntlm Ntlm Specifies NTLM authentication.
AuthenticationSchemeSelector AuthenticationScheme
Selector Delegate
Selects the authentication scheme for an HttpListener instance.

D eclaration
public delegate System.Net.AuthenticationSchemes
AuthenticationSchemeSelector(HttpListenerRequest httpRequest);
type AuthenticationSchemeSelector = delegate of HttpListenerRequest -> AuthenticationSchemes

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
Delegates of this type are used by HttpListener instances to select an authentication scheme based on the
characteristics of a request.
An AuthenticationSchemeSelector delegate is passed an HttpListenerRequest object for each incoming request that
has not provided authentication information. The method invoked by the delegate uses the HttpListenerRequest object
and any other available information to decide which authentication scheme to require. The delegate is specified by
using the AuthenticationSchemeSelectorDelegate property.
Authorization Authorization Class
Contains an authentication message for an Internet server.

D eclaration
public class Authorization
type Authorization = class

I nheritance H ierarchy
Object Object

Remarks
The AuthenticationManager returns an instance of the Authorization class that contains an authentication message.
This message is sent to the Internet server to indicate that the client (such as WebRequest or one of its descendants) is
authorized to access the server.
The Authorization instance is created by the authentication module that the AuthenticationManager designates to
handle the request.

Constructors
Authorization(String)
Authorization(String)

Creates a new instance of the Authorization class with the specified authorization message.

Authorization(String, Boolean)
Authorization(String, Boolean)

Creates a new instance of the Authorization class with the specified authorization message and completion status.

Authorization(String, Boolean, String)


Authorization(String, Boolean, String)

Creates a new instance of the Authorization class with the specified authorization message, completion status, and
connection group identifier.

Properties
Complete
Complete

Gets the completion status of the authorization.

ConnectionGroupId
ConnectionGroupId
Gets a unique identifier for user-specific connections.

Message
Message

Gets the message returned to the server in response to an authentication challenge.

MutuallyAuthenticated
MutuallyAuthenticated

Gets or sets a Boolean value that indicates whether mutual authentication occurred.

ProtectionRealm
ProtectionRealm

Gets or sets the prefix for Uniform Resource Identifiers (URIs) that can be authenticated with the Message
property.
Authorization Authorization
I n this Article

Overloads
Authorization(String) Authorization(String)
Creates a new instance of the Authorization class with the
specified authorization message.

Authorization(String, Boolean) Authorization(String, Boolean)


Creates a new instance of the Authorization class with the
specified authorization message and completion status.

Authorization(String, Boolean, String) Authorization(String,


Boolean, String) Creates a new instance of the Authorization class with the
specified authorization message, completion status, and
connection group identifier.

Authorization(String) Authorization(String)
Creates a new instance of the Authorization class with the specified authorization message.
public Authorization (string token);
new System.Net.Authorization : string -> System.Net.Authorization

Parameters
token String String
The encrypted authorization message expected by the server.
Examples
The following code example shows how to create an Authorization object. For a complete example, refer to the
AuthenticationManager class.
// Authenticate is the core method for this custom authentication.
// When an Internet resource requests authentication, the WebRequest.GetResponse
// method calls the AuthenticationManager.Authenticate method. This method, in
// turn, calls the Authenticate method on each of the registered authentication
// modules, in the order in which they were registered. When the authentication is
// complete an Authorization object is returned to the WebRequest.
public Authorization Authenticate(String challenge, WebRequest request, ICredentials credentials)
{
Encoding ASCII = Encoding.ASCII;

// Get the username and password from the credentials


NetworkCredential MyCreds = credentials.GetCredential(request.RequestUri, "Basic");

if (PreAuthenticate(request, credentials) == null)


Console.WriteLine("
Pre-authentication is not allowed.");
else
Console.WriteLine("
Pre-authentication is allowed.");

// Verify that the challenge satisfies the authorization requirements.


bool challengeOk = checkChallenge(challenge, MyCreds.Domain);

if (!challengeOk)
return null;

// Create the encrypted string according to the Basic authentication format as


// follows:
// a)Concatenate the username and password separated by colon;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 encoding to this array of bytes to obtain the encoded
// authorization.
string BasicEncrypt = MyCreds.UserName + ":" + MyCreds.Password;

string BasicToken = "Basic " + Convert.ToBase64String(ASCII.GetBytes(BasicEncrypt));

// Create an Authorization object using the encoded authorization above.


Authorization resourceAuthorization = new Authorization(BasicToken);

// Get the Message property, which contains the authorization string that the
// client returns to the server when accessing protected resources.
Console.WriteLine("
Authorization Message:{0}",resourceAuthorization.Message);

// Get the Complete property, which is set to true when the authentication process
// between the client and the server is finished.
Console.WriteLine("
Authorization Complete:{0}",resourceAuthorization.Complete);

Console.WriteLine("
Authorization ConnectionGroupId:{0}",resourceAuthorization.ConnectionGroupId);

return resourceAuthorization;
}

Remarks
The Authorization instance is created with the Message property set to token and the Complete property set to true .

Authorization(String, Boolean) Authorization(String, Boolean)


Creates a new instance of the Authorization class with the specified authorization message and completion status.
public Authorization (string token, bool finished);
new System.Net.Authorization : string * bool -> System.Net.Authorization

Parameters
token String String
The encrypted authorization message expected by the server.
finished Boolean Boolean
The completion status of the authorization attempt. true if the authorization attempt is complete; otherwise, false .
Examples
The following code example creates a new instance of the Authorization class with the specified authorization message
and completion status.
public Authorization Authenticate( string challenge,WebRequest request,ICredentials credentials)
{
try
{
string message;
// Check if Challenge string was raised by a site which requires 'CloneBasic'
authentication.
if ((challenge == null) || (!challenge.StartsWith("CloneBasic")))
return null;
NetworkCredential myCredentials;
if (credentials is CredentialCache)
{
myCredentials = credentials.GetCredential(request.RequestUri,"CloneBasic");
if (myCredentials == null)
return null;
}
else
myCredentials = (NetworkCredential)credentials;
// Message encryption scheme :
// a)Concatenate username and password seperated by space;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 Encoding to this array of bytes to obtain our encoded authorization
message.

message = myCredentials.UserName + " " + myCredentials.Password;


// Apply AsciiEncoding to 'message' string to obtain it as an array of bytes.
Encoding ascii = Encoding.ASCII;
byte[] byteArray = new byte[ascii.GetByteCount(message)];
byteArray = ascii.GetBytes(message);

// Performing Base64 transformation.


message = Convert.ToBase64String(byteArray);
Authorization myAuthorization = new Authorization("CloneBasic " + message,true);
string[] protectionRealm = new string[]{request.RequestUri.AbsolutePath};
myAuthorization.ProtectionRealm = protectionRealm;

return myAuthorization;
}
catch(Exception e)
{
Console.WriteLine("The following exception was raised in Authenticate method:
{0}",e.Message);
return null;
}
}
Remarks
The Authorization instance is created with the Message property set to token and the Complete property set to
finished .

Authorization(String, Boolean, String) Authorization(String,


Boolean, String)
Creates a new instance of the Authorization class with the specified authorization message, completion status, and
connection group identifier.
public Authorization (string token, bool finished, string connectionGroupId);
new System.Net.Authorization : string * bool * string -> System.Net.Authorization

Parameters
token String String
The encrypted authorization message expected by the server.
finished Boolean Boolean
The completion status of the authorization attempt. true if the authorization attempt is complete; otherwise, false .
connectionGroupId String String
A unique identifier that can be used to create private client-server connections that are bound only to this
authentication scheme.
Examples
The following code example creates a new instance of the Authorization class with the specified authorization message,
completion status, and connection group identifier.
public Authorization Authenticate( string challenge,WebRequest request,ICredentials credentials)
{
try
{
string message;
// Check if Challenge string was raised by a site which requires CloneBasic authentication.
if ((challenge == null) || (!challenge.StartsWith("CloneBasic")))
return null;
NetworkCredential myCredentials;
if (credentials is CredentialCache)
{
myCredentials = credentials.GetCredential(request.RequestUri,"CloneBasic");
if (myCredentials == null)
return null;
}
else
myCredentials = (NetworkCredential)credentials;
// Message encryption scheme :
// a)Concatenate username and password seperated by space;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 Encoding to this array of bytes to obtain our encoded authorization message.

message = myCredentials.UserName + " " + myCredentials.Password;


// Apply AsciiEncoding to our user name and password to obtain it as an array of bytes.
Encoding asciiEncoding = Encoding.ASCII;
byte[] byteArray = new byte[asciiEncoding.GetByteCount(message)];
byteArray = asciiEncoding.GetBytes(message);

// Perform Base64 transform.


message = Convert.ToBase64String(byteArray);
// The following overloaded contructor sets the 'Message' property of authorization to the
base64 string;
// that we just formed and it also sets the 'Complete' property to true and the connection
group id;
// to the domain of the NetworkCredential object.
Authorization myAuthorization = new Authorization("CloneBasic " +
message,true,request.ConnectionGroupName);
return myAuthorization;
}
catch(Exception e)
{
Console.WriteLine("Exception Raised ...:"+e.Message);
return null;
}
}
Authorization.Complete Authorization.Complete
I n this Article
Gets the completion status of the authorization.
public bool Complete { get; }
member this.Complete : bool

Returns
Boolean Boolean
true if the authentication process is complete; otherwise, false .

Examples
The following code example uses the Complete property to get the completion status of the authorization. For a
complete example, refer to the AuthenticationManager class.
// Create the encrypted string according to the Basic authentication format as
// follows:
// a)Concatenate the username and password separated by colon;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 encoding to this array of bytes to obtain the encoded
// authorization.
string BasicEncrypt = MyCreds.UserName + ":" + MyCreds.Password;

string BasicToken = "Basic " + Convert.ToBase64String(ASCII.GetBytes(BasicEncrypt));

// Create an Authorization object using the encoded authorization above.


Authorization resourceAuthorization = new Authorization(BasicToken);

// Get the Message property, which contains the authorization string that the
// client returns to the server when accessing protected resources.
Console.WriteLine("
Authorization Message:{0}",resourceAuthorization.Message);

// Get the Complete property, which is set to true when the authentication process
// between the client and the server is finished.
Console.WriteLine("
Authorization Complete:{0}",resourceAuthorization.Complete);

Remarks
The Complete property is set to true when the authentication process between the client and the server is finished.
Some authentication modules, such as the Kerberos module, use multiple round trips between the client and server to
complete the authentication process. To keep the WebRequest or descendant that initiated the authentication process
from interrupting while authorization is taking place, the authentication module sets the Complete property to false .
Authorization.ConnectionGroupId Authorization.
ConnectionGroupId
I n this Article
Gets a unique identifier for user-specific connections.

public string ConnectionGroupId { get; }


member this.ConnectionGroupId : string

Returns
String String
A unique string that associates a connection with an authenticating entity.

Examples
The following code example uses the ConnectionGroupId property to get the group identifier returned by the server.
For a complete example, refer to the AuthenticationManager class.
// Create the encrypted string according to the Basic authentication format as
// follows:
// a)Concatenate the username and password separated by colon;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 encoding to this array of bytes to obtain the encoded
// authorization.
string BasicEncrypt = MyCreds.UserName + ":" + MyCreds.Password;

string BasicToken = "Basic " + Convert.ToBase64String(ASCII.GetBytes(BasicEncrypt));

// Create an Authorization object using the encoded authorization above.


Authorization resourceAuthorization = new Authorization(BasicToken);

// Get the Message property, which contains the authorization string that the
// client returns to the server when accessing protected resources.
Console.WriteLine("
Authorization Message:{0}",resourceAuthorization.Message);

// Get the Complete property, which is set to true when the authentication process
// between the client and the server is finished.
Console.WriteLine("
Authorization Complete:{0}",resourceAuthorization.Complete);

Remarks
The ConnectionGroupId property is a unique string that associates a connection with a specific authenticating entity.
For example, the NTLM authorization module ties the authentication credential information to a specific connection to
prevent invalid reuse of the connection.
Authorization.Message Authorization.Message
I n this Article
Gets the message returned to the server in response to an authentication challenge.
public string Message { get; }
member this.Message : string

Returns
String String
The message that will be returned to the server in response to an authentication challenge.

Examples
The following code example uses the Message property to get the message returned to the server in response to an
authentication challenge. For a complete example, refer to the AuthenticationManager class.
// Create the encrypted string according to the Basic authentication format as
// follows:
// a)Concatenate the username and password separated by colon;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 encoding to this array of bytes to obtain the encoded
// authorization.
string BasicEncrypt = MyCreds.UserName + ":" + MyCreds.Password;

string BasicToken = "Basic " + Convert.ToBase64String(ASCII.GetBytes(BasicEncrypt));

// Create an Authorization object using the encoded authorization above.


Authorization resourceAuthorization = new Authorization(BasicToken);

// Get the Message property, which contains the authorization string that the
// client returns to the server when accessing protected resources.
Console.WriteLine("
Authorization Message:{0}",resourceAuthorization.Message);

// Get the Complete property, which is set to true when the authentication process
// between the client and the server is finished.
Console.WriteLine("
Authorization Complete:{0}",resourceAuthorization.Complete);

Remarks
The Message property contains the authorization string that the client will return to the server when accessing
protected resources. The actual contents of the message are defined by the authentication type the client and server are
using. Basic HTTP authentication, for example, uses a different message than Kerberos authentication.
When an authentication module supports preauthentication, the Message property is sent with the initial request.
Authorization.MutuallyAuthenticated Authorization.
MutuallyAuthenticated
I n this Article
Gets or sets a Boolean value that indicates whether mutual authentication occurred.

public bool MutuallyAuthenticated { get; set; }


member this.MutuallyAuthenticated : bool with get, set

Returns
Boolean Boolean
true if both client and server were authenticated; otherwise, false .

Remarks
This property returns false if the authentication has not completed.
Authorization.ProtectionRealm Authorization.Protection
Realm
I n this Article
Gets or sets the prefix for Uniform Resource Identifiers (URIs) that can be authenticated with the Message property.

public string[] ProtectionRealm { get; set; }


member this.ProtectionRealm : string[] with get, set

Returns
String[]
An array of strings that contains URI prefixes.

Examples
The following code example gets or sets the prefix for URIs that can be authenticated with the Message property.
public Authorization Authenticate( string challenge,WebRequest request,ICredentials credentials)
{
try
{
string message;
// Check if Challenge string was raised by a site which requires 'CloneBasic'
authentication.
if ((challenge == null) || (!challenge.StartsWith("CloneBasic")))
return null;
NetworkCredential myCredentials;
if (credentials is CredentialCache)
{
myCredentials = credentials.GetCredential(request.RequestUri,"CloneBasic");
if (myCredentials == null)
return null;
}
else
myCredentials = (NetworkCredential)credentials;
// Message encryption scheme :
// a)Concatenate username and password seperated by space;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 Encoding to this array of bytes to obtain our encoded authorization
message.

message = myCredentials.UserName + " " + myCredentials.Password;


// Apply AsciiEncoding to 'message' string to obtain it as an array of bytes.
Encoding ascii = Encoding.ASCII;
byte[] byteArray = new byte[ascii.GetByteCount(message)];
byteArray = ascii.GetBytes(message);

// Performing Base64 transformation.


message = Convert.ToBase64String(byteArray);
Authorization myAuthorization = new Authorization("CloneBasic " + message,true);
string[] protectionRealm = new string[]{request.RequestUri.AbsolutePath};
myAuthorization.ProtectionRealm = protectionRealm;

return myAuthorization;
}
catch(Exception e)
{
Console.WriteLine("The following exception was raised in Authenticate method:
{0}",e.Message);
return null;
}
}

Remarks
The ProtectionRealm property contains a list of URI prefixes that the Message property can be used to authenticate.
WebRequest and its descendants compare a URI to this list to determine if the Authorization is valid for a particular
URI.
BindIPEndPoint BindIPEndPoint Delegate
Represents the method that specifies a local Internet Protocol address and port number for a ServicePoint.

D eclaration
public delegate System.Net.IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint
remoteEndPoint, int retryCount);
type BindIPEndPoint = delegate of ServicePoint * IPEndPoint * int -> IPEndPoint

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
Specify that the BindIPEndPoint delegate is used by a ServicePoint by setting the
ServicePoint.BindIPEndPointDelegate property with the delegate as an argument. This delegate should specify a local
IP address and port number in the returned IPEndPoint.
If the .NET Framework cannot bind the returned IPEndPoint to the ServicePoint after Int32.MaxValue attempts, an
OverflowException is thrown.
If you want the delegate to give the service point control of the connection binding, the delegate should return null . If
you want to abort the connection, the delegate must throw an exception.
CipherSuitesCallback CipherSuitesCallback Delegate
D eclaration
[System.Obsolete("This API is no longer supported.")]
public delegate System.Collections.Generic.IEnumerable<string>
CipherSuitesCallback(SecurityProtocolType protocol, IEnumerable<string> allCiphers);
type CipherSuitesCallback = delegate of SecurityProtocolType * seq<string> -> seq<string>

I nheritance H ierarchy
Object Object
Delegate Delegate
Cookie Cookie Class
Provides a set of properties and methods that are used to manage cookies. This class cannot be inherited.

D eclaration
[System.Serializable]
public sealed class Cookie
type Cookie = class

I nheritance H ierarchy
Object Object

Remarks
The Cookie class is used by a client application to retrieve information about cookies that are received with HTTP
responses. The following cookie formats are supported during parsing of the HTTP response headers: the original
Netscape specification, RFC 2109, and RFC 2965.
For a list of initial property values for an instance of Cookie, see the various Cookie constructors.

Constructors
Cookie()
Cookie()

Initializes a new instance of the Cookie class.

Cookie(String, String)
Cookie(String, String)

Initializes a new instance of the Cookie class with a specified Name and Value.

Cookie(String, String, String)


Cookie(String, String, String)

Initializes a new instance of the Cookie class with a specified Name, Value, and Path.

Cookie(String, String, String, String)


Cookie(String, String, String, String)

Initializes a new instance of the Cookie class with a specified Name, Value, Path, and Domain.

Properties
Comment
Comment

Gets or sets a comment that the server can add to a Cookie.


CommentUri
CommentUri

Gets or sets a URI comment that the server can provide with a Cookie.

Discard
Discard

Gets or sets the discard flag set by the server.

Domain
Domain

Gets or sets the URI for which the Cookie is valid.

Expired
Expired

Gets or sets the current state of the Cookie.

Expires
Expires

Gets or sets the expiration date and time for the Cookie as a DateTime.

HttpOnly
HttpOnly

Determines whether a page script or other active content can access this cookie.

Name
Name

Gets or sets the name for the Cookie.

Path
Path

Gets or sets the URIs to which the Cookie applies.

Port
Port

Gets or sets a list of TCP ports that the Cookie applies to.
Secure
Secure

Gets or sets the security level of a Cookie.

TimeStamp
TimeStamp

Gets the time when the cookie was issued as a DateTime.

Value
Value

Gets or sets the Value for the Cookie.

Version
Version

Gets or sets the version of HTTP state maintenance to which the cookie conforms.

Methods
Equals(Object)
Equals(Object)

Overrides the Equals(Object) method.

GetHashCode()
GetHashCode()

Overrides the GetHashCode() method.

ToString()
ToString()

Overrides the ToString() method.

See Also
CookieException CookieException
Cookie.Comment Cookie.Comment
I n this Article
Gets or sets a comment that the server can add to a Cookie.
public string Comment { get; set; }
member this.Comment : string with get, set

Returns
String String
An optional comment to document intended usage for this Cookie.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
The client can inspect this optional comment for information added by the server. For example, the server could include
information about issues like the privacy policy or intended usage.
See CookieExceptionCookieException
Also
Cookie.CommentUri Cookie.CommentUri
I n this Article
Gets or sets a URI comment that the server can provide with a Cookie.
public Uri CommentUri { get; set; }
member this.CommentUri : Uri with get, set

Returns
Uri Uri
An optional comment that represents the intended usage of the URI reference for this Cookie. The value must conform
to URI format.

Examples
The following example displays the properties of cookies that are returned in a response. For the complete example,
see the Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
The URI can provide optional information, such as how the server uses the Cookie.
See CookieExceptionCookieException
Also
Cookie Cookie
I n this Article

Overloads
Cookie()
Initializes a new instance of the Cookie class.

Cookie(String, String) Cookie(String, String)


Initializes a new instance of the Cookie class with a specified
Name and Value.

Cookie(String, String, String) Cookie(String, String, String)


Initializes a new instance of the Cookie class with a specified
Name, Value, and Path.

Cookie(String, String, String, String) Cookie(String, String,


String, String) Initializes a new instance of the Cookie class with a specified
Name, Value, Path, and Domain.

Cookie()
Initializes a new instance of the Cookie class.
public Cookie ();

Remarks
The default constructor initializes all fields to their default values, using empty strings ("") for name , value , path , and
domain . Note that at least the Name property must be initialized before using an instance of the Cookie class.

Cookie(String, String) Cookie(String, String)


Initializes a new instance of the Cookie class with a specified Name and Value.
public Cookie (string name, string value);
new System.Net.Cookie : string * string -> System.Net.Cookie

Parameters
name String String
The name of a Cookie. The following characters must not be used inside name : equal sign, semicolon, comma, newline
(\n), return (\r), tab (\t), and space character. The dollar sign character ("$") cannot be the first character.

value String String


The value of a Cookie. The following characters must not be used inside value : semicolon, comma.
Exceptions
CookieException CookieException
The name parameter is null .
-or-
The name parameter is of zero length.
-or-
The name parameter contains an invalid character.
-or-
The value parameter is null .
-or -
The value parameter contains a string not enclosed in quotes that contains an invalid character.
Remarks
The default for the value parameter uses the empty string ("").
The value parameter for a Cookie must not be a null reference (Nothing in Visual Basic). The semicolon (";") and
comma (",") characters are reserved and cannot be passed in the value parameter unless the string passed in the
value parameter is enclosed in double quotes. So the following example constructor would succeed, but when you try
to add this Cookie to a CookieContainer instance with the Add(Cookie) or Add(Uri, Cookie) methods, the operation will
fail and throw an exception:

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "123,456");


cookie.Domain = "contoso.com";
new CookieContainer().Add(cookie);

However, the following constructor with these special characters escaped will create a Cookie that can be added to a
CookieContainer instance:

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "\"123,456\"");


cookie.Domain = "contoso.com";
new CookieContainer().Add(cookie);

The comma character is used as a delimiter between separate cookies on the same line.
See CookieExceptionCookieException
Also

Cookie(String, String, String) Cookie(String, String, String)


Initializes a new instance of the Cookie class with a specified Name, Value, and Path.
public Cookie (string name, string value, string path);
new System.Net.Cookie : string * string * string -> System.Net.Cookie

Parameters
name String String
The name of a Cookie. The following characters must not be used inside name : equal sign, semicolon, comma, newline
(\n), return (\r), tab (\t), and space character. The dollar sign character ("$") cannot be the first character.

value String String


The value of a Cookie. The following characters must not be used inside value : semicolon, comma.
path String String
The subset of URIs on the origin server to which this Cookie applies. The default value is "/".
Exceptions
CookieException CookieException
The name parameter is null .
-or-
The name parameter is of zero length.
-or-
The name parameter contains an invalid character.
-or-
The value parameter is null .
-or -
The value parameter contains a string not enclosed in quotes that contains an invalid character.
Remarks
The default for the path parameter uses the empty string ("").

The value parameter for a Cookie must not be a null reference (Nothing in Visual Basic). The semicolon (";") and
comma (",") characters are reserved and cannot be passed in the value parameter unless the string passed in the
value parameter is enclosed in double quotes. So the following example constructor would succeed, but when you try
to add this Cookie to a CookieContainer instance with the Add(Cookie) or Add(Uri, Cookie) methods, the operation will
fail and throw an exception:
System.Net.Cookie cookie = new System.Net.Cookie("contoso", "123,456", "");
cookie.Domain = "contoso.com";
new CookieContainer().Add(cookie);

However, the following constructor with these special characters escaped will create a Cookie that can be added to a
CookieContainer instance:

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "\"123,456\"", "");


cookie.Domain = "contoso.com";
new CookieContainer().Add(cookie);

The comma character is used as a delimiter between separate cookies on the same line.
See CookieExceptionCookieException
Also

Cookie(String, String, String, String) Cookie(String, String, String,


String)
Initializes a new instance of the Cookie class with a specified Name, Value, Path, and Domain.
public Cookie (string name, string value, string path, string domain);
new System.Net.Cookie : string * string * string * string -> System.Net.Cookie
Parameters
name String String
The name of a Cookie. The following characters must not be used inside name : equal sign, semicolon, comma, newline
(\n), return (\r), tab (\t), and space character. The dollar sign character ("$") cannot be the first character.

value String String


The value of a Cookie object. The following characters must not be used inside value : semicolon, comma.

path String String


The subset of URIs on the origin server to which this Cookie applies. The default value is "/".
domain String String
The optional internet domain for which this Cookie is valid. The default value is the host this Cookie has been received
from.
Exceptions
CookieException CookieException
The name parameter is null .
-or-
The name parameter is of zero length.
-or-
The name parameter contains an invalid character.
-or-
The value parameter is null .
-or -
The value parameter contains a string not enclosed in quotes that contains an invalid character.
Remarks
The default for the domain and path parameters uses the empty string ("").

The value parameter for a Cookie must not be a null reference (Nothing in Visual Basic). The semicolon (";") and
comma (",") characters are reserved and cannot be passed in the value parameter unless the string passed in the
value parameter is enclosed in double quotes. So the following example constructor would succeed, but when you try
to add this Cookie to a CookieContainer instance with the Add(Cookie) or Add(Uri, Cookie) methods, the operation will
fail and throw an exception:

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "123,456", "", "contoso.com");


new CookieContainer().Add(cookie);

However, the following constructor with these special characters escaped will create a Cookie that can be added to a
CookieContainer instance:

System.Net.Cookie cookie = new System.Net.Cookie("contoso", "\"123,456\"", "", "contoso.com");


new CookieContainer().Add(cookie);

The comma character is used as a delimiter between separate cookies on the same line.
See CookieExceptionCookieException
Also
Cookie.Discard Cookie.Discard
I n this Article
Gets or sets the discard flag set by the server.
public bool Discard { get; set; }
member this.Discard : bool with get, set

Returns
Boolean Boolean
true if the client is to discard the Cookie at the end of the current session; otherwise, false . The default is false .

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
When true , this property instructs the client application not to save the Cookie on the user's hard disk when a session
ends.
See CookieExceptionCookieException
Also
Cookie.Domain Cookie.Domain
I n this Article
Gets or sets the URI for which the Cookie is valid.
public string Domain { get; set; }
member this.Domain : string with get, set

Returns
String String
The URI for which the Cookie is valid.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
A server cannot indicate a domain other than its own URI. However, it can indicate more than one server in the
domain. The default value is the host that this cookie has been received from.
See CookieExceptionCookieException
Also
Cookie.Equals Cookie.Equals
I n this Article
Overrides the Equals(Object) method.
public override bool Equals (object comparand);
override this.Equals : obj -> bool

Parameters
comparand Object Object
A reference to a Cookie.
Returns
Boolean Boolean
Returns true if the Cookie is equal to comparand . Two Cookie instances are equal if their Name, Value, Path, Domain,
and Version properties are equal. Name and Domain string comparisons are case-insensitive.
See CookieExceptionCookieException
Also
Cookie.Expired Cookie.Expired
I n this Article
Gets or sets the current state of the Cookie.
public bool Expired { get; set; }
member this.Expired : bool with get, set

Returns
Boolean Boolean
true if the Cookie has expired; otherwise, false . The default is false .

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
Expired cookies, if received, should be destroyed by the client application.
See CookieExceptionCookieException
Also
Cookie.Expires Cookie.Expires
I n this Article
Gets or sets the expiration date and time for the Cookie as a DateTime.
public DateTime Expires { get; set; }
member this.Expires : DateTime with get, set

Returns
DateTime DateTime
The expiration date and time for the Cookie as a DateTime instance.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
Setting the Expires property to DateTime makes this a session Cookie, which is its default value.
The DateTimeKind property of Expires is used to determine if the Cookie is set in DateTimeKind or DateTimeKind. If
the DateTimeKind property is set to DateTimeKind, then DateTimeKind is assumed.
See CookieExceptionCookieException
Also
Cookie.GetHashCode Cookie.GetHashCode
I n this Article
Overrides the GetHashCode() method.
public override int GetHashCode ();
override this.GetHashCode : unit -> int

Returns
Int32 Int32
The 32-bit signed integer hash code for this instance.

Remarks
Classes that might be used as a key in a hash table must provide this override, because objects that are used as keys in
a hash table are required to generate their own hash code through this method.
Cookie.HttpOnly Cookie.HttpOnly
I n this Article
Determines whether a page script or other active content can access this cookie.
public bool HttpOnly { get; set; }
member this.HttpOnly : bool with get, set

Returns
Boolean Boolean
Boolean value that determines whether a page script or other active content can access this cookie.

Remarks
When this property is set to true , a page script or other active content cannot access this cookie.
Cookie.Name Cookie.Name
I n this Article
Gets or sets the name for the Cookie.
public string Name { get; set; }
member this.Name : string with get, set

Returns
String String
The name for the Cookie.
Exceptions
CookieException CookieException
The value specified for a set operation is null or the empty string
-or-
The value specified for a set operation contained an illegal character. The following characters must not be used inside
the Name property: equal sign, semicolon, comma, newline (\n), return (\r), tab (\t), and space character. The dollar sign
character ("$") cannot be the first character.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}
Remarks
The Name property must be initialized before using an instance of the Cookie class.
The following characters are reserved and cannot be used for this attribute value: equal sign, semicolon, comma, new
line (\n), return (\r), tab (\t), and space character. The dollar sign ($) character cannot be the first character.
See CookieExceptionCookieException
Also
Cookie.Path Cookie.Path
I n this Article
Gets or sets the URIs to which the Cookie applies.
public string Path { get; set; }
member this.Path : string with get, set

Returns
String String
The URIs to which the Cookie applies.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
The Path property specifies the subset of URIs on the origin server to which this Cookie applies. If this property is not
specified, then this Cookie will be sent to all pages on the origin server or servers.
See CookieExceptionCookieException
Also
Cookie.Port Cookie.Port
I n this Article
Gets or sets a list of TCP ports that the Cookie applies to.
public string Port { get; set; }
member this.Port : string with get, set

Returns
String String
The list of TCP ports that the Cookie applies to.
Exceptions
CookieException CookieException
The value specified for a set operation could not be parsed or is not enclosed in double quotes.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
This attribute restricts the ports to which this Cookie may be sent. The default value means no restriction. Setting this
to the empty string ("") will restrict the port to the one used in the HTTP response. Otherwise, the value must be a
double-quoted string that contains port values delimited with commas.
See CookieExceptionCookieException
Also
Cookie.Secure Cookie.Secure
I n this Article
Gets or sets the security level of a Cookie.
public bool Secure { get; set; }
member this.Secure : bool with get, set

Returns
Boolean Boolean
true if the client is only to return the cookie in subsequent requests if those requests use Secure Hypertext Transfer
Protocol (HTTPS ); otherwise, false . The default is false .

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
In effect, when this property is true this cookie may be sent only with https:// requests.
See CookieExceptionCookieException
Also
Cookie.TimeStamp Cookie.TimeStamp
I n this Article
Gets the time when the cookie was issued as a DateTime.
public DateTime TimeStamp { get; }
member this.TimeStamp : DateTime

Returns
DateTime DateTime
The time when the cookie was issued as a DateTime.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
This is a read-only property.
See CookieExceptionCookieException
Also
Cookie.ToString Cookie.ToString
I n this Article
Overrides the ToString() method.
public override string ToString ();
override this.ToString : unit -> string

Returns
String String
Returns a string representation of this Cookie object that is suitable for including in a HTTP Cookie: request header.

Examples
The following example displays the string value of a cookie returned in a response. For the complete example, see the
Cookie class topic.
// Show the string representation of the cookie.
Console.WriteLine ("String: {0}", cook.ToString());

Remarks
The exact format of the string depends on the RFC that this cookie conforms to.
Cookie.Value Cookie.Value
I n this Article
Gets or sets the Value for the Cookie.
public string Value { get; set; }
member this.Value : string with get, set

Returns
String String
The Value for the Cookie.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
The Value of a Cookie must not be null . If a null value is assigned to this property, it's replaced with an empty string.
Semicolons and commas are reserved characters that cannot be used in the value of this property. Assigning invalid
characters to this property doesn't throw an exception; but when you try to add this Cookie to a CookieContainer
instance with the Add method, the operation will fail and throw an exception.
See CookieExceptionCookieException
Also
Cookie.Version Cookie.Version
I n this Article
Gets or sets the version of HTTP state maintenance to which the cookie conforms.
public int Version { get; set; }
member this.Version : int with get, set

Returns
Int32 Int32
The version of HTTP state maintenance to which the cookie conforms.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for a version is not allowed.

Examples
The following example displays the properties of cookies returned in a response. For the complete example, see the
Cookie class topic.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}

Remarks
The default value for the Version property is 0, complying with the original Netscape specification. If the value is
explicitly set to 1, then this Cookie must conform to RFC 2109. Note that if a Cookie was created automatically by
receiving a Set-Cookie2 HTTP response header, the conformance is set to RFC 2965.
An attempt to set the Version property to a value less than zero will throw an exception.
See CookieExceptionCookieException
Also
CookieCollection CookieCollection Class
Provides a collection container for instances of the Cookie class.

D eclaration
[System.Serializable]
public class CookieCollection : System.Collections.ICollection
type CookieCollection = class
interface ICollection
interface IEnumerable

I nheritance H ierarchy
Object Object

Remarks
The CookieCollection class implements an ICollection interface to provide a general mechanism for handling
collections of cookies. For example, this is useful in the case where an application is designed to store cookies for
multiple servers.

Constructors
CookieCollection()
CookieCollection()

Initializes a new instance of the CookieCollection class.

Properties
Count
Count

Gets the number of cookies contained in a CookieCollection.

IsReadOnly
IsReadOnly

Gets a value that indicates whether a CookieCollection is read-only.

IsSynchronized
IsSynchronized

Gets a value that indicates whether access to a CookieCollection is thread safe.

Item[Int32]
Item[Int32]

Gets the Cookie with a specific index from a CookieCollection.


Item[String]
Item[String]

Gets the Cookie with a specific name from a CookieCollection.

SyncRoot
SyncRoot

Gets an object to synchronize access to the CookieCollection.

Methods
Add(Cookie)
Add(Cookie)

Adds a Cookie to a CookieCollection.

Add(CookieCollection)
Add(CookieCollection)

Adds the contents of a CookieCollection to the current instance.

Clear()
Clear()

Contains(Cookie)
Contains(Cookie)

CopyTo(Array, Int32)
CopyTo(Array, Int32)

Copies the elements of a CookieCollection to an instance of the Array class, starting at a particular index.

CopyTo(Cookie[], Int32)
CopyTo(Cookie[], Int32)

Copies the elements of this CookieCollection to a Cookie array starting at the specified index of the target array.

GetEnumerator()
GetEnumerator()

Gets an enumerator that can iterate through a CookieCollection.


Remove(Cookie)
Remove(Cookie)

IEnumerable<Cookie>.GetEnumerator()
IEnumerable<Cookie>.GetEnumerator()

ICollection.CopyTo(Array, Int32)
ICollection.CopyTo(Array, Int32)

ICollection.IsSynchronized
ICollection.IsSynchronized

ICollection.SyncRoot
ICollection.SyncRoot

See Also
Cookie Cookie
CookieCollection CookieCollection
ICollection ICollection
CookieCollection.Add CookieCollection.Add
I n this Article

Overloads
Add(Cookie) Add(Cookie)
Adds a Cookie to a CookieCollection.

Add(CookieCollection) Add(CookieCollection)
Adds the contents of a CookieCollection to the current
instance.

Add(Cookie) Add(Cookie)
Adds a Cookie to a CookieCollection.
public void Add (System.Net.Cookie cookie);
member this.Add : System.Net.Cookie -> unit

Parameters
cookie Cookie Cookie
The Cookie to be added to a CookieCollection.
Exceptions
ArgumentNullException ArgumentNullException
cookie is null .
See CookieCollectionCookieCollection
Also

Add(CookieCollection) Add(CookieCollection)
Adds the contents of a CookieCollection to the current instance.
public void Add (System.Net.CookieCollection cookies);
member this.Add : System.Net.CookieCollection -> unit

Parameters
cookies CookieCollection CookieCollection
The CookieCollection to be added.
Exceptions
ArgumentNullException ArgumentNullException
cookies is null .
Remarks
Each Cookie is read from the CookieCollection cookies parameter and added to the current instance.
See CookieCollectionCookieCollection
Also
CookieCollection.Clear CookieCollection.Clear
I n this Article
public void Clear ();
abstract member Clear : unit -> unit
override this.Clear : unit -> unit
CookieCollection.Contains CookieCollection.Contains
I n this Article
public bool Contains (System.Net.Cookie cookie);
abstract member Contains : System.Net.Cookie -> bool
override this.Contains : System.Net.Cookie -> bool

Parameters
cookie Cookie Cookie
Returns
Boolean Boolean
CookieCollection
I n this Article
Initializes a new instance of the CookieCollection class.
public CookieCollection ();

Remarks
The following table shows initial property values for an instance of CookieCollection.

PR O PER T Y D EFAU LT

IsReadOnly true

Count 0

IsSynchronized false

See Cookie
Also CookieCollection
CookieCollection.CopyTo CookieCollection.CopyTo
I n this Article

Overloads
CopyTo(Array, Int32) CopyTo(Array, Int32)
Copies the elements of a CookieCollection to an instance of
the Array class, starting at a particular index.

CopyTo(Cookie[], Int32) CopyTo(Cookie[], Int32)


Copies the elements of this CookieCollection to a Cookie array
starting at the specified index of the target array.

CopyTo(Array, Int32) CopyTo(Array, Int32)


Copies the elements of a CookieCollection to an instance of the Array class, starting at a particular index.
public void CopyTo (Array array, int index);
abstract member CopyTo : Array * int -> unit
override this.CopyTo : Array * int -> unit

Parameters
array Array Array
The target Array to which the CookieCollection will be copied.
index Int32 Int32
The zero-based index in the target Array where copying begins.
Exceptions
ArgumentNullException ArgumentNullException
array is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
index is less than zero.
ArgumentException ArgumentException
array is multidimensional.
-or-
The number of elements in this CookieCollection is greater than the available space from index to the end of the
destination array .
InvalidCastException InvalidCastException
The elements in this CookieCollection cannot be cast automatically to the type of the destination array .
Remarks
The Array array parameter must be one-dimensional with zero-based indexing.
CopyTo(Cookie[], Int32) CopyTo(Cookie[], Int32)
Copies the elements of this CookieCollection to a Cookie array starting at the specified index of the target array.
public void CopyTo (System.Net.Cookie[] array, int index);
member this.CopyTo : System.Net.Cookie[] * int -> unit

Parameters
array Cookie[]
The target Cookie array to which the CookieCollection will be copied.
index Int32 Int32
The zero-based index in the target Array where copying begins.
Exceptions
ArgumentNullException ArgumentNullException
array is null .

ArgumentOutOfRangeException ArgumentOutOfRangeException
index is less than zero.
ArgumentException ArgumentException
array is multidimensional.
-or-
The number of elements in this CookieCollection is greater than the available space from index to the end of the
destination array .

InvalidCastException InvalidCastException
The elements in this CookieCollection cannot be cast automatically to the type of the destination array .
Remarks
The Array array parameter must be one-dimensional with zero-based indexing.
CookieCollection.Count CookieCollection.Count
I n this Article
Gets the number of cookies contained in a CookieCollection.
public int Count { get; }
member this.Count : int

Returns
Int32 Int32
The number of cookies contained in a CookieCollection.
See CookieCookie
Also CookieCollectionCookieCollection
CookieCollection.GetEnumerator CookieCollection.Get
Enumerator
I n this Article
Gets an enumerator that can iterate through a CookieCollection.

public System.Collections.IEnumerator GetEnumerator ();


abstract member GetEnumerator : unit -> System.Collections.IEnumerator
override this.GetEnumerator : unit -> System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
An instance of an implementation of an IEnumerator interface that can iterate through a CookieCollection.

Remarks
You should use an IEnumerator only to read data in the collection. Enumerators cannot be used to modify the
underlying collection. The enumerator does not have exclusive access to the collection.
When an enumerator is created, it takes a snapshot of the current state of the collection. If changes are made to the
collection, such as adding, modifying, or deleting elements, this snapshot gets out of sync and the enumerator throws
an InvalidOperationException. Two enumerators created from the same collection at the same time can produce
different snapshots of the collection.
CookieCollection.ICollection.CopyTo
I n this Article
void ICollection.CopyTo (Array array, int index);

Parameters
array Array
index Int32
CookieCollection.ICollection.IsSynchronized
I n this Article
bool System.Collections.ICollection.IsSynchronized { get; }

Returns
Boolean
CookieCollection.ICollection.SyncRoot
I n this Article
object System.Collections.ICollection.SyncRoot { get; }

Returns
Object
CookieCollection.IEnumerable<Cookie>.GetEnumerator
I n this Article
System.Collections.Generic.IEnumerator<System.Net.Cookie> IEnumerable<Cookie>.GetEnumerator ();

Returns
IEnumerator<Cookie>
CookieCollection.IsReadOnly CookieCollection.IsRead
Only
I n this Article
Gets a value that indicates whether a CookieCollection is read-only.

public bool IsReadOnly { get; }


member this.IsReadOnly : bool

Returns
Boolean Boolean
true if this is a read-only CookieCollection; otherwise, false . The default is true .

See CookieCollectionCookieCollection
Also
CookieCollection.IsSynchronized CookieCollection.Is
Synchronized
I n this Article
Gets a value that indicates whether access to a CookieCollection is thread safe.

public bool IsSynchronized { get; }


member this.IsSynchronized : bool

Returns
Boolean Boolean
true if access to the CookieCollection is thread safe; otherwise, false . The default is false .
CookieCollection.Item[String] CookieCollection.Item[
String]
I n this Article

Overloads
Item[Int32] Item[Int32]
Gets the Cookie with a specific index from a CookieCollection.

Item[String] Item[String]
Gets the Cookie with a specific name from a CookieCollection.

Item[Int32] Item[Int32]
Gets the Cookie with a specific index from a CookieCollection.
public System.Net.Cookie this[int index] { get; }
member this.Item(int) : System.Net.Cookie

Parameters
index Int32 Int32
The zero-based index of the Cookie to be found.
Returns
Cookie Cookie
A Cookie with a specific index from a CookieCollection.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
index is less than 0 or index is greater than or equal to Count.
Examples
// Get the cookies in the 'CookieCollection' object using the 'Item' property.
// The 'Item' property in C# is implemented through Indexers.
// The class that implements indexers is usually a collection of other objects.
// This class provides access to those objects with the '<class-instance>[i]' syntax.
try {
if(cookies.Count == 0) {
Console.WriteLine("No cookies to display");
return;
}
for(int j = 0; j < cookies.Count; j++)
Console.WriteLine("{0}", cookies[j].ToString());
Console.WriteLine("");
}
catch(Exception e) {
Console.WriteLine("Exception raised.
Error : " + e.Message);
}

Remarks
You can use this to iterate over the contents of a CookieCollection.
See CookieCollectionCookieCollection
Also

Item[String] Item[String]
Gets the Cookie with a specific name from a CookieCollection.
public System.Net.Cookie this[string name] { get; }
member this.Item(string) : System.Net.Cookie

Parameters
name String String
The name of the Cookie to be found.
Returns
Cookie Cookie
The Cookie with a specific name from a CookieCollection.
Exceptions
ArgumentNullException ArgumentNullException
name is null .
Examples
// Get the cookies in the 'CookieCollection' object using the 'Item' property.
// The 'Item' property in C# is implemented through Indexers.
// The class that implements indexers is usually a collection of other objects.
// This class provides access to those objects with the '<class-instance>[i]' syntax.
try {
if(cookies.Count == 0) {
Console.WriteLine("No cookies to display");
return;
}
Console.WriteLine("{0}", cookies["UserName"].ToString());
Console.WriteLine("{0}", cookies["DateOfBirth"].ToString());
Console.WriteLine("{0}", cookies["PlaceOfBirth"].ToString());
Console.WriteLine("");
}
catch(Exception e) {
Console.WriteLine("Exception raised.
Error : " + e.Message);
}

Remarks
You can use this to iterate over the contents of a CookieCollection.
See CookieCollectionCookieCollection
Also
CookieCollection.Remove CookieCollection.Remove
I n this Article
public bool Remove (System.Net.Cookie cookie);
abstract member Remove : System.Net.Cookie -> bool
override this.Remove : System.Net.Cookie -> bool

Parameters
cookie Cookie Cookie
Returns
Boolean Boolean
CookieCollection.SyncRoot CookieCollection.SyncRoot
I n this Article
Gets an object to synchronize access to the CookieCollection.
public object SyncRoot { get; }
member this.SyncRoot : obj

Returns
Object Object
An object to synchronize access to the CookieCollection.

Remarks
The SyncRoot property returns an object that can be used to synchronize access to the CookieCollection.
See ICollectionICollection
Also
CookieContainer CookieContainer Class
Provides a container for a collection of CookieCollection objects.

D eclaration
[System.Serializable]
public class CookieContainer
type CookieContainer = class

I nheritance H ierarchy
Object Object

Remarks
A CookieContainer is a data structure that provides storage for instances of the Cookie class, and which is accessed in a
database-like manner. The CookieContainer has a capacity limit that is set when the container is created or changed by
a property.
An instance of the Cookie class is added to the container based on its originating URI. It is added to an internal
CookieCollection associated with the URI. A Cookie is retrieved from the container based on the URI as a
CookieCollection, or as a string that can be used to submit HTTP WebRequests.
The CookieContainer has three properties that govern the volume of the content of the container: Capacity,
MaxCookieSize, and PerDomainCapacity. These values have the default settings of 300, 4096, and 20 respectively.
When a Cookie is added to the container, these properties are used to determine whether a Cookie already contained
in the CookieContainer should be discarded to make room for the new one. The CookieContainer keeps track of each
addition to ensure that neither the Capacity nor the PerDomainCapacity limits are exceeded. If one or both are
exceeded, then Cookie instances held by the CookieContainer are removed. First, any expired Cookie is removed. If
further capacity must be recaptured, then the least-recently used CookieCollection is purged.

Constructors
CookieContainer()
CookieContainer()

Initializes a new instance of the CookieContainer class.

CookieContainer(Int32)
CookieContainer(Int32)

Initializes a new instance of the CookieContainer class with a specified value for the number of Cookie instances
that the container can hold.

CookieContainer(Int32, Int32, Int32)


CookieContainer(Int32, Int32, Int32)

Initializes a new instance of the CookieContainer class with specific properties.


Fields
DefaultCookieLengthLimit
DefaultCookieLengthLimit

Represents the default maximum size, in bytes, of the Cookie instances that the CookieContainer can hold. This
field is constant.

DefaultCookieLimit
DefaultCookieLimit

Represents the default maximum number of Cookie instances that the CookieContainer can hold. This field is
constant.

DefaultPerDomainCookieLimit
DefaultPerDomainCookieLimit

Represents the default maximum number of Cookie instances that the CookieContainer can reference per domain.
This field is constant.

Properties
Capacity
Capacity

Gets or sets the number of Cookie instances that a CookieContainer can hold.

Count
Count

Gets the number of Cookie instances that a CookieContainer currently holds.

MaxCookieSize
MaxCookieSize

Represents the maximum allowed length of a Cookie.

PerDomainCapacity
PerDomainCapacity

Gets or sets the number of Cookie instances that a CookieContainer can hold per domain.

Methods
Add(Cookie)
Add(Cookie)
Adds a Cookie to a CookieContainer. This method uses the domain from the Cookie to determine which domain
collection to associate the Cookie with.

Add(CookieCollection)
Add(CookieCollection)

Adds the contents of a CookieCollection to the CookieContainer.

Add(Uri, Cookie)
Add(Uri, Cookie)

Adds a Cookie to the CookieContainer for a particular URI.

Add(Uri, CookieCollection)
Add(Uri, CookieCollection)

Adds the contents of a CookieCollection to the CookieContainer for a particular URI.

GetCookieHeader(Uri)
GetCookieHeader(Uri)

Gets the HTTP cookie header that contains the HTTP cookies that represent the Cookie instances that are
associated with a specific URI.

GetCookies(Uri)
GetCookies(Uri)

Gets a CookieCollection that contains the Cookie instances that are associated with a specific URI.

SetCookies(Uri, String)
SetCookies(Uri, String)

Adds Cookie instances for one or more cookies from an HTTP cookie header to the CookieContainer for a specific
URI.

See Also
Cookie Cookie
CookieCollection CookieCollection
CookieException CookieException
CookieContainer.Add CookieContainer.Add
I n this Article

Overloads
Add(Cookie) Add(Cookie)
Adds a Cookie to a CookieContainer. This method uses the
domain from the Cookie to determine which domain collection
to associate the Cookie with.

Add(CookieCollection) Add(CookieCollection)
Adds the contents of a CookieCollection to the
CookieContainer.

Add(Uri, Cookie) Add(Uri, Cookie)


Adds a Cookie to the CookieContainer for a particular URI.

Add(Uri, CookieCollection) Add(Uri, CookieCollection)


Adds the contents of a CookieCollection to the
CookieContainer for a particular URI.

Add(Cookie) Add(Cookie)
Adds a Cookie to a CookieContainer. This method uses the domain from the Cookie to determine which domain
collection to associate the Cookie with.
public void Add (System.Net.Cookie cookie);
member this.Add : System.Net.Cookie -> unit

Parameters
cookie Cookie Cookie
The Cookie to be added to the CookieContainer.
Exceptions
ArgumentNullException ArgumentNullException
cookie is null .
ArgumentException ArgumentException
The domain for cookie is null or the empty string ("").
CookieException CookieException
cookie is larger than maxCookieSize .
-or-
the domain for cookie is not a valid URI.
Remarks
If the Count property equals or exceeds the Capacity property, one or more Cookie instances are removed from the
container before adding the cookie parameter. Enough Cookie instances are removed to bring Count below Capacity
as follows: if there are expired instances in the given scope, they are cleaned up. If not, then the least recently used
CookieCollection is found and removed from the container.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException

Add(CookieCollection) Add(CookieCollection)
Adds the contents of a CookieCollection to the CookieContainer.
public void Add (System.Net.CookieCollection cookies);
member this.Add : System.Net.CookieCollection -> unit

Parameters
cookies CookieCollection CookieCollection
The CookieCollection to be added to the CookieContainer.
Exceptions
ArgumentNullException ArgumentNullException
cookies is null .
Remarks
If the Count property equals the Capacity property, one or more Cookie instances are removed from the container
before adding the contents of the cookies parameter. Enough Cookie instances are removed to make room for
cookies as follows: if there are expired instances, they are cleaned up. If not, or if more room is needed, then the least
recently used CookieCollection is found and removed from the container.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException

Add(Uri, Cookie) Add(Uri, Cookie)


Adds a Cookie to the CookieContainer for a particular URI.
public void Add (Uri uri, System.Net.Cookie cookie);
member this.Add : Uri * System.Net.Cookie -> unit

Parameters
uri Uri Uri
The URI of the Cookie to be added to the CookieContainer.
cookie Cookie Cookie
The Cookie to be added to the CookieContainer.
Exceptions
ArgumentNullException ArgumentNullException
uri is null or cookie is null .

CookieException CookieException
cookie is larger than maxCookieSize .
-or-
The domain for cookie is not a valid URI.
Remarks
If you add a Cookie instance for just one specific host, do not set the Domain property of the Cookie instance. This is
set automatically, based on the URI.
If your URI corresponds to your local domain and sends to all the hosts on the local domain, set the CookieDomain
property equal to ".local". Otherwise, make sure it matches the host name used in the URI.
If the Version property of a Cookie is Netscape, the Path property of the Cookie, if not set explicitly, is derived from the
URI and is the complete path from the URI, including the page name.
If the Count property equals the Capacity property, one or more Cookie instances are removed from the container
before adding the cookie parameter. Enough Cookie instances are removed to bring Count below Capacity as follows:
if there are expired instances in scope, they are cleaned up. If not, then the least recently used CookieCollection is found
and removed from the container.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException

Add(Uri, CookieCollection) Add(Uri, CookieCollection)


Adds the contents of a CookieCollection to the CookieContainer for a particular URI.

public void Add (Uri uri, System.Net.CookieCollection cookies);


member this.Add : Uri * System.Net.CookieCollection -> unit

Parameters
uri Uri Uri
The URI of the CookieCollection to be added to the CookieContainer.
cookies CookieCollection CookieCollection
The CookieCollection to be added to the CookieContainer.
Exceptions
ArgumentNullException ArgumentNullException
cookies is null .

ArgumentException ArgumentException
The domain for one of the cookies in cookies is null .

CookieException CookieException
One of the cookies in cookies contains an invalid domain.
Remarks
If you add a Cookie instance for just one specific host, do not set the Domain property of the Cookie instance. This is
set automatically, based on the URI.
If your URI corresponds to your local domain and sends to all the hosts on the local domain, set the CookieDomain
property equal to ".local". Otherwise, make sure it matches the host name used in the URI.
If Count equals Capacity, one or more Cookie instances is removed from the container before adding the cookie
parameter. Enough Cookie instances are removed to bring Count below Capacity as follows: if there are expired
instances in scope they are cleaned up. If not, then the least recently used CookieCollection is found and removed from
the container.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.Capacity CookieContainer.Capacity
I n this Article
Gets or sets the number of Cookie instances that a CookieContainer can hold.
public int Capacity { get; set; }
member this.Capacity : int with get, set

Returns
Int32 Int32
The number of Cookie instances that a CookieContainer can hold. This is a hard limit and cannot be exceeded by
adding a Cookie.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
Capacity is less than or equal to zero or (value is less than PerDomainCapacity and PerDomainCapacity is not equal
to MaxValue).

Remarks
If Count equals or exceeds Capacity, one or more Cookie instances are removed from the container. Enough instances
are removed to bring Count below Capacity as follows: if there are expired Cookie instances in scope, they are cleaned
up. If not, then the least recently used CookieCollection is found and removed from the container.
Capacity must be greater than or equal to PerDomainCapacity.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer CookieContainer
I n this Article

Overloads
CookieContainer()
Initializes a new instance of the CookieContainer class.

CookieContainer(Int32) CookieContainer(Int32)
Initializes a new instance of the CookieContainer class with a
specified value for the number of Cookie instances that the
container can hold.

CookieContainer(Int32, Int32, Int32) CookieContainer(Int32,


Int32, Int32) Initializes a new instance of the CookieContainer class with
specific properties.

CookieContainer()
Initializes a new instance of the CookieContainer class.
public CookieContainer ();

Remarks
The default constructor initializes all fields to their default values. DefaultCookieLimit is used to initialize Capacity,
DefaultCookieLengthLimit is used for MaxCookieSize, and DefaultPerDomainCookieLimit is used for
PerDomainCapacity.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException

CookieContainer(Int32) CookieContainer(Int32)
Initializes a new instance of the CookieContainer class with a specified value for the number of Cookie instances that
the container can hold.
public CookieContainer (int capacity);
new System.Net.CookieContainer : int -> System.Net.CookieContainer

Parameters
capacity Int32 Int32
The number of Cookie instances that the CookieContainer can hold.
Exceptions
ArgumentException ArgumentException
capacity is less than or equal to zero.
Remarks
PerDomainCapacity is initialized to 20, and MaxCookieSize is initialized to 4096.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException

CookieContainer(Int32, Int32, Int32) CookieContainer(Int32, Int32,


Int32)
Initializes a new instance of the CookieContainer class with specific properties.
public CookieContainer (int capacity, int perDomainCapacity, int maxCookieSize);
new System.Net.CookieContainer : int * int * int -> System.Net.CookieContainer

Parameters
capacity Int32 Int32
The number of Cookie instances that the CookieContainer can hold.
perDomainCapacity Int32 Int32
The number of Cookie instances per domain.
maxCookieSize Int32 Int32
The maximum size in bytes for any single Cookie in a CookieContainer.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
perDomainCapacity is not equal to MaxValue.

and
(perDomainCapacity is less than or equal to zero or perDomainCapacity is greater than capacity) .
ArgumentException ArgumentException
maxCookieSize is less than or equal to zero.
Remarks
The parameters specify values for Capacity, MaxCookieSize, and PerDomainCapacity.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.Count CookieContainer.Count
I n this Article
Gets the number of Cookie instances that a CookieContainer currently holds.
public int Count { get; }
member this.Count : int

Returns
Int32 Int32
The number of Cookie instances that a CookieContainer currently holds. This is the total of Cookie instances in all
domains.

Remarks
The default value of this property is DefaultCookieLimit. If Count equals or exceeds Capacity, one or more Cookie
instances are removed from the container. Enough instances are removed to bring Count below Capacity as follows: if
there are expired Cookie instances in scope, they are cleaned up. If not, then the least recently used CookieCollection is
found and removed from the container.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.DefaultCookieLengthLimit Cookie
Container.DefaultCookieLengthLimit
I n this Article
Represents the default maximum size, in bytes, of the Cookie instances that the CookieContainer can hold. This field is
constant.
public const int DefaultCookieLengthLimit = 4096;
val mutable DefaultCookieLengthLimit : int

Returns
Int32 Int32

Remarks
The default maximum Cookie size is 4096.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.DefaultCookieLimit CookieContainer.
DefaultCookieLimit
I n this Article
Represents the default maximum number of Cookie instances that the CookieContainer can hold. This field is constant.

public const int DefaultCookieLimit = 300;


val mutable DefaultCookieLimit : int

Returns
Int32 Int32

Remarks
The default maximum number of Cookie instances is 300.
See CookieCollectionCookieCollection
Also CookieExceptionCookieException
CookieContainer.DefaultPerDomainCookieLimit Cookie
Container.DefaultPerDomainCookieLimit
I n this Article
Represents the default maximum number of Cookie instances that the CookieContainer can reference per domain. This
field is constant.
public const int DefaultPerDomainCookieLimit = 20;
val mutable DefaultPerDomainCookieLimit : int

Returns
Int32 Int32

Remarks
The default maximum number of Cookie instances per domain is 20.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.GetCookieHeader CookieContainer.Get
CookieHeader
I n this Article
Gets the HTTP cookie header that contains the HTTP cookies that represent the Cookie instances that are associated
with a specific URI.
public string GetCookieHeader (Uri uri);
member this.GetCookieHeader : Uri -> string

Parameters
uri Uri Uri
The URI of the Cookie instances desired.
Returns
String String
An HTTP cookie header, with strings representing Cookie instances delimited by semicolons.
Exceptions
ArgumentNullException ArgumentNullException
uri is null .

Remarks
GetCookieHeader returns a string that holds the HTTP cookie header for the Cookie instances specified by uri . The
HTTP header is built by adding a string representation of each Cookie associated with uri . Note that the exact format
of the string depends on the RFC that the Cookie conforms to. The strings for all the Cookie instances that are
associated with uri are combined and delimited by semicolons.
This string is not in the correct format for use as the second parameter of the SetCookies method.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.GetCookies CookieContainer.Get
Cookies
I n this Article
Gets a CookieCollection that contains the Cookie instances that are associated with a specific URI.

public System.Net.CookieCollection GetCookies (Uri uri);


member this.GetCookies : Uri -> System.Net.CookieCollection

Parameters
uri Uri Uri
The URI of the Cookie instances desired.
Returns
CookieCollection CookieCollection
A CookieCollection that contains the Cookie instances that are associated with a specific URI.
Exceptions
ArgumentNullException ArgumentNullException
uri is null .

Remarks
A new instance of a CookieCollection is created. Then the Cookie instances in the internal collection that are associated
with the specified URI are read out and added to the new CookieCollection.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.MaxCookieSize CookieContainer.Max
CookieSize
I n this Article
Represents the maximum allowed length of a Cookie.

public int MaxCookieSize { get; set; }


member this.MaxCookieSize : int with get, set

Returns
Int32 Int32
The maximum allowed length, in bytes, of a Cookie.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
MaxCookieSize is less than or equal to zero.

Remarks
If the new value of MaxCookieSize is less than the current value, any Cookie with a length that exceeds the new value
will be truncated.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.PerDomainCapacity CookieContainer.
PerDomainCapacity
I n this Article
Gets or sets the number of Cookie instances that a CookieContainer can hold per domain.

public int PerDomainCapacity { get; set; }


member this.PerDomainCapacity : int with get, set

Returns
Int32 Int32
The number of Cookie instances that are allowed per domain.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
PerDomainCapacity is less than or equal to zero.
-or-
(PerDomainCapacity is greater than the maximum allowable number of cookies instances, 300, and is not equal to
MaxValue).

Remarks
If the new PerDomainCapacity value is less than the current value, and if any of the domain collections contain more
Cookie instances than the new value, the collections are pruned to fit. This uses the same basic rules as described in the
Capacity property. However, this does the clean-up only on the collection for this domain.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieContainer.SetCookies CookieContainer.SetCookies
I n this Article
Adds Cookie instances for one or more cookies from an HTTP cookie header to the CookieContainer for a specific URI.
public void SetCookies (Uri uri, string cookieHeader);
member this.SetCookies : Uri * string -> unit

Parameters
uri Uri Uri
The URI of the CookieCollection.
cookieHeader String String
The contents of an HTTP set-cookie header as returned by a HTTP server, with Cookie instances delimited by commas.
Exceptions
ArgumentNullException ArgumentNullException
uri or cookieHeader is null .
CookieException CookieException
One of the cookies is invalid.
-or-
An error occurred while adding one of the cookies to the container.

Remarks
SetCookies pulls all the HTTP cookies out of the HTTP cookie header, builds a Cookie for each one, and then adds each
Cookie to the internal CookieCollection that is associated with the URI. The HTTP cookies in the cookieHeader string
must be delimited by commas.
See CookieCookie
Also CookieCollectionCookieCollection
CookieExceptionCookieException
CookieException CookieException Class
The exception that is thrown when an error is made adding a Cookie to a CookieContainer.

D eclaration
[System.Serializable]
public class CookieException : FormatException
type CookieException = class
inherit FormatException
interface ISerializable

I nheritance H ierarchy
Object Object
Exception Exception
SystemException SystemException
FormatException FormatException

Remarks
This exception is thrown if an attempt is made to Add a Cookie with length greater than MaxCookieSize to a
CookieContainer.
Associated Tips
Make sure the cookie size does not exceed the maximum allowed by the cookie container.
This exception is thrown when an attempt is made to add a Cookie with length greater than MaxCookieSize to a
CookieContainer. The default maximum cookie size is 4096 bytes.
When setting the Name property for a cookie, make sure the value is not a null reference or empty string.
The Name property must be initialized before using an instance of the Cookie class. The following characters are
reserved and cannot be used for this attribute value: equal sign, semicolon, comma, new line (\n), carriage return (\r),
tab (\t). The dollar sign ($) character cannot be the first character.
When setting the Port property for a cookie, make sure the value is valid and enclosed in double quotes.
The Port attribute restricts the ports to which a cookie may be sent. The default value means no restriction. Setting the
property to an empty string ("") restricts the port to the one used in the HTTP response. Otherwise the value must be a
string in quotation marks that contains port values delineated with commas.
When setting the Value property for a cookie, make sure the value is not null.
The following characters are reserved and cannot be used for this property: semicolon, comma.

Constructors
CookieException()
CookieException()

Initializes a new instance of the CookieException class.

CookieException(SerializationInfo, StreamingContext)
CookieException(SerializationInfo, StreamingContext)

Initializes a new instance of the CookieException class with specific values of serializationInfo and
streamingContext .

Methods
GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo instance with the data needed to serialize the CookieException.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo instance with the data needed to serialize the CookieException.

See Also
ISerializable ISerializable
CookieException CookieException
I n this Article

Overloads
CookieException()
Initializes a new instance of the CookieException class.

CookieException(SerializationInfo, StreamingContext) Cookie


Exception(SerializationInfo, StreamingContext) Initializes a new instance of the CookieException class with
specific values of serializationInfo and
streamingContext .

CookieException()
Initializes a new instance of the CookieException class.
public CookieException ();

Remarks
The default constructor for CookieException.
See ISerializableISerializable
Also

CookieException(SerializationInfo, StreamingContext)
CookieException(SerializationInfo, StreamingContext)
Initializes a new instance of the CookieException class with specific values of serializationInfo and
streamingContext .

protected CookieException (System.Runtime.Serialization.SerializationInfo serializationInfo,


System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.CookieException : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.CookieException

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to be used.
streamingContext StreamingContext StreamingContext
The StreamingContext to be used.
Remarks
Allows you to set up custom serialization.
See ISerializableISerializable
Also
CookieException.GetObjectData CookieException.Get
ObjectData
I n this Article
Populates a SerializationInfo instance with the data needed to serialize the CookieException.

public override void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The object that holds the serialized object data. The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
The contextual information about the source or destination. A StreamingContext that specifies the destination for this
serialization.

Remarks
This constructor is called during deserialization to reconstitute the exception object transmitted over a stream. For
more information, see XML and SOAP Serialization. Any objects included in the SerializationInfo are automatically
tracked and serialized by the formatter.
CookieException.ISerializable.GetObjectData
I n this Article
Populates a SerializationInfo instance with the data needed to serialize the CookieException.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The SerializationInfo to be used.
streamingContext StreamingContext
The StreamingContext to be used.
See ISerializable
Also
CredentialCache CredentialCache Class
Provides storage for multiple credentials.

D eclaration
public class CredentialCache : System.Collections.IEnumerable, System.Net.ICredentials,
System.Net.ICredentialsByHost
type CredentialCache = class
interface ICredentials
interface ICredentialsByHost
interface IEnumerable

I nheritance H ierarchy
Object Object

Remarks
The CredentialCache class stores credentials for multiple Internet resources. Applications that need to access multiple
resources can store the credentials for those resources in a CredentialCache instance that then provides the proper set
of credentials to the Internet resource when required. When the GetCredential method is called, it compares the
Uniform Resource Identifier (URI) and authentication type provided with those stored in the cache and returns the first
set of credentials that match.
The DefaultCredentials property contains the system credentials of the current security context. For client applications,
these represent the user name, password, and domain of the user who is currently logged in. For ASP.NET
applications, the default credentials are the user credentials of the logged-in user or the user being impersonated.

Constructors
CredentialCache()
CredentialCache()

Creates a new instance of the CredentialCache class.

Properties
DefaultCredentials
DefaultCredentials

Gets the system credentials of the application.

DefaultNetworkCredentials
DefaultNetworkCredentials

Gets the network credentials of the current security context.

Methods
Add(Uri, String, NetworkCredential)
Add(Uri, String, NetworkCredential)

Adds a NetworkCredential instance to the credential cache for use with protocols other than SMTP and associates
it with a Uniform Resource Identifier (URI) prefix and authentication protocol.

Add(String, Int32, String, NetworkCredential)


Add(String, Int32, String, NetworkCredential)

Adds a NetworkCredential instance for use with SMTP to the credential cache and associates it with a host
computer, port, and authentication protocol. Credentials added using this method are valid for SMTP only. This
method does not work for HTTP or FTP requests.

GetCredential(Uri, String)
GetCredential(Uri, String)

Returns the NetworkCredential instance associated with the specified Uniform Resource Identifier (URI) and
authentication type.

GetCredential(String, Int32, String)


GetCredential(String, Int32, String)

Returns the NetworkCredential instance associated with the specified host, port, and authentication protocol.

GetEnumerator()
GetEnumerator()

Returns an enumerator that can iterate through the CredentialCache instance.

Remove(Uri, String)
Remove(Uri, String)

Deletes a NetworkCredential instance from the cache if it is associated with the specified Uniform Resource
Identifier (URI) prefix and authentication protocol.

Remove(String, Int32, String)


Remove(String, Int32, String)

Deletes a NetworkCredential instance from the cache if it is associated with the specified host, port, and
authentication protocol.

See Also
ICredentials ICredentials
CredentialCache.Add CredentialCache.Add
I n this Article

Overloads
Add(Uri, String, NetworkCredential) Add(Uri, String, Network
Credential) Adds a NetworkCredential instance to the credential cache for
use with protocols other than SMTP and associates it with a
Uniform Resource Identifier (URI) prefix and authentication
protocol.

Add(String, Int32, String, NetworkCredential) Add(String,


Int32, String, NetworkCredential) Adds a NetworkCredential instance for use with SMTP to the
credential cache and associates it with a host computer, port,
and authentication protocol. Credentials added using this
method are valid for SMTP only. This method does not work
for HTTP or FTP requests.

Add(Uri, String, NetworkCredential) Add(Uri, String,


NetworkCredential)
Adds a NetworkCredential instance to the credential cache for use with protocols other than SMTP and associates it
with a Uniform Resource Identifier (URI) prefix and authentication protocol.
public void Add (Uri uriPrefix, string authType, System.Net.NetworkCredential cred);
member this.Add : Uri * string * System.Net.NetworkCredential -> unit

Parameters
uriPrefix Uri Uri
A Uri that specifies the URI prefix of the resources that the credential grants access to.
authType String String
The authentication scheme used by the resource named in uriPrefix .
cred NetworkCredential NetworkCredential
The NetworkCredential to add to the credential cache.
Exceptions
ArgumentNullException ArgumentNullException
uriPrefix is null .
-or-
authType is null .
ArgumentException ArgumentException
The same credentials are added more than once.
Examples
The following code example initializes a CredentialCache with multiple security credentials and uses those credentials
with a WebRequest.
CredentialCache myCache = new CredentialCache();

myCache.Add(new Uri("http://www.contoso.com/"),"Basic",new
NetworkCredential(UserName,SecurelyStoredPassword));
myCache.Add(new Uri("http://www.contoso.com/"),"Digest", new
NetworkCredential(UserName,SecurelyStoredPassword,Domain));

wReq.Credentials = myCache;

Remarks
The Add method places a NetworkCredential instance for use with protocols other than SMTP into the
CredentialCache. The cache stores credentials in the order in which they are added to it. When the GetCredential(Uri,
String) method is called, it returns the proper matching NetworkCredential instance.

Add(String, Int32, String, NetworkCredential) Add(String, Int32,


String, NetworkCredential)
Adds a NetworkCredential instance for use with SMTP to the credential cache and associates it with a host computer,
port, and authentication protocol. Credentials added using this method are valid for SMTP only. This method does not
work for HTTP or FTP requests.
public void Add (string host, int port, string authenticationType, System.Net.NetworkCredential
credential);
member this.Add : string * int * string * System.Net.NetworkCredential -> unit

Parameters
host String String
A String that identifies the host computer.
port Int32 Int32
A Int32 that specifies the port to connect to on host .
authenticationType String String
A String that identifies the authentication scheme used when connecting to host using cred .
credential NetworkCredential NetworkCredential
The NetworkCredential to add to the credential cache.
Exceptions
ArgumentNullException ArgumentNullException
host is null .
-or-
authType is null .
ArgumentException ArgumentException
authType not an accepted value.
ArgumentOutOfRangeException ArgumentOutOfRangeException
port is less than zero.
Examples
The following code example initializes a CredentialCache with multiple security credentials for use with SMTP and uses
one of those credentials with a SmtpClient.
SmtpClient client = new SmtpClient("ContosoMail", 45);
MailAddress from = new MailAddress("sender@SenderMailServerName.com", "Sender Name");
MailAddress to = new MailAddress("recepient@RecepientMailServerName.com", "Recepient Name");
MailMessage message = new MailMessage(from, to);

message.Body = "This is a test email message sent by an application. ";


message.Subject = "Test Email using Credentials";

NetworkCredential myCreds = new NetworkCredential("username", "password", "domain");


CredentialCache myCredentialCache = new CredentialCache();
try
{
myCredentialCache.Add("ContoscoMail", 35, "Basic", myCreds);
myCredentialCache.Add("ContoscoMail", 45, "NTLM", myCreds);

client.Credentials = myCredentialCache.GetCredential("ContosoMail", 45, "NTLM");


client.Send(message);
Console.WriteLine("Goodbye.");
}
catch(Exception e)
{
Console.WriteLine("Exception is raised. ");
Console.WriteLine("Message: {0} ",e.Message);
}

Remarks
This method places a NetworkCredential instance for use with SMTP into the CredentialCache. The cache stores
credentials in the order in which they are added to it. When the GetCredential(String, Int32, String) method is called, it
returns a NetworkCredential instance that is selected by matching the host , port , and authType . The comparison is
done case-insensitively.
The supported values for authType are "NTLM", "Digest", "Kerberos", and "Negotiate".
Credentials added with this method are only valid for use with SMTP. This method does not work for HTTP or FTP
protocols.
CredentialCache
I n this Article
Creates a new instance of the CredentialCache class.
public CredentialCache ();

Examples
The following code example initializes a CredentialCache with multiple security credentials and uses those credentials
with a WebRequest.
CredentialCache myCache = new CredentialCache();

myCache.Add(new Uri("http://www.contoso.com/"),"Basic",new
NetworkCredential(UserName,SecurelyStoredPassword));
myCache.Add(new Uri("http://www.contoso.com/"),"Digest", new
NetworkCredential(UserName,SecurelyStoredPassword,Domain));

wReq.Credentials = myCache;

Remarks
The constructor creates a CredentialCache instance.
CredentialCache.DefaultCredentials CredentialCache.
DefaultCredentials
I n this Article
Gets the system credentials of the application.

public static System.Net.ICredentials DefaultCredentials { get; }


member this.DefaultCredentials : System.Net.ICredentials

Returns
ICredentials ICredentials
An ICredentials that represents the system credentials of the application.

Examples
The following code example uses the DefaultCredentials property to get the system credentials of the application.
// Ensure Directory Security settings for default web site in IIS is "Windows Authentication".
string url = "http://localhost";
// Create a 'HttpWebRequest' object with the specified url.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Assign the credentials of the logged in user or the user being impersonated.
myHttpWebRequest.Credentials = CredentialCache.DefaultCredentials;
// Send the 'HttpWebRequest' and wait for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine("Authentication successful");
Console.WriteLine("Response received successfully");

Remarks
The DefaultCredentials property applies only to NTLM, negotiate, and Kerberos-based authentication.
DefaultCredentials represents the system credentials for the current security context in which the application is
running. For a client-side application, these are usually the Windows credentials (user name, password, and domain) of
the user running the application. For ASP.NET applications, the default credentials are the user credentials of the
logged-in user, or the user being impersonated.
To get the credentials as a NetworkCredential instance, use the DefaultNetworkCredentials property.
The supported values for authType are "NTLM", "Digest", "Kerberos", and "Negotiate". This method does not work for
HTTP or FTP protocols.
Note

The ICredentials instance returned by DefaultCredentials cannot be used to view the user name, password, or domain
of the current security context.
CredentialCache.DefaultNetworkCredentials Credential
Cache.DefaultNetworkCredentials
I n this Article
Gets the network credentials of the current security context.

public static System.Net.NetworkCredential DefaultNetworkCredentials { get; }


member this.DefaultNetworkCredentials : System.Net.NetworkCredential

Returns
NetworkCredential NetworkCredential
An NetworkCredential that represents the network credentials of the current user or application.

Remarks
The credentials returned by the DefaultNetworkCredentials property is applicable only for NTLM, negotiate, and
Kerberos-based authentication.
The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current
security context in which the application is running. For a client-side application, these are usually the Windows
credentials (user name, password, and domain) of the user running the application. For ASP.NET applications, the
default network credentials are the user credentials of the logged-in user, or the user being impersonated.
CredentialCache.GetCredential CredentialCache.Get
Credential
I n this Article

Overloads
GetCredential(Uri, String) GetCredential(Uri, String)
Returns the NetworkCredential instance associated with the
specified Uniform Resource Identifier (URI) and authentication
type.

GetCredential(String, Int32, String) GetCredential(String, Int32,


String) Returns the NetworkCredential instance associated with the
specified host, port, and authentication protocol.

GetCredential(Uri, String) GetCredential(Uri, String)


Returns the NetworkCredential instance associated with the specified Uniform Resource Identifier (URI) and
authentication type.
public System.Net.NetworkCredential GetCredential (Uri uriPrefix, string authType);
abstract member GetCredential : Uri * string -> System.Net.NetworkCredential
override this.GetCredential : Uri * string -> System.Net.NetworkCredential

Parameters
uriPrefix Uri Uri
A Uri that specifies the URI prefix of the resources that the credential grants access to.
authType String String
The authentication scheme used by the resource named in uriPrefix .
Returns
NetworkCredential NetworkCredential
A NetworkCredential or, if there is no matching credential in the cache, null .
Exceptions
ArgumentNullException ArgumentNullException
uriPrefix or authType is null .
Examples
The following code example uses the GetCredential(Uri, String) method to return the NetworkCredential instance
associated with the specified URI and authentication type.
public static void GetPage(string url,string userName,string password,string domainName)
{
try
{
CredentialCache myCredentialCache = new CredentialCache();
// Dummy names used as credentials.
myCredentialCache.Add(new Uri("http://microsoft.com/"),"Basic", new
NetworkCredential("user1","passwd1","domain1"));
myCredentialCache.Add(new Uri("http://msdn.com/"),"Basic", new
NetworkCredential("user2","passwd2","domain2"));
myCredentialCache.Add(new Uri(url),"Basic", new
NetworkCredential(userName,password,domainName));
// Create a webrequest with the specified url.
WebRequest myWebRequest = WebRequest.Create(url);
// Call 'GetCredential' to obtain the credentials specific to our Uri.
NetworkCredential myCredential = myCredentialCache.GetCredential(new Uri(url),"Basic");
Display(myCredential);
// Associating only our credentials.
myWebRequest.Credentials = myCredential;
// Sends the request and waits for response.
WebResponse myWebResponse = myWebRequest.GetResponse();

// Process response here.

Console.WriteLine("
Response Received.");
myWebResponse.Close();

}
catch(WebException e)
{
if (e.Response != null)
Console.WriteLine("\r
Failed to obtain a response. The following error occured : {0}",((HttpWebResponse)
(e.Response)).StatusDescription);
else
Console.WriteLine("\r
Failed to obtain a response. The following error occured : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following exception was raised : {0}",e.Message);
}
}
public static void Display(NetworkCredential credential)
{
Console.WriteLine("
The credentials are:");
Console.WriteLine("
Username : {0} ,Password : {1} ,Domain :
{2}",credential.UserName,credential.Password,credential.Domain);
}

Remarks
The GetCredential(Uri, String) method searches the CredentialCache and returns the NetworkCredential instance for
the specified URI and authorization type. If the CredentialCache contains no matching NetworkCredential instance,
null is returned.

GetCredential uses the longest matching URI prefix in the cache to determine which set of credentials to return for an
authorization type. The following table shows examples.
U R I PR EFIX MATCHES

http://www.contoso.com/portal/news.htm Requests for the specific Web page news.htm .

http://www.contoso.com/portal/ Requests for all content in the portal path, except the page
news.htm .

http://www.contoso.com/ Requests for all resources at www.contoso.com , except


those in the portal path.

GetCredential(String, Int32, String) GetCredential(String, Int32,


String)
Returns the NetworkCredential instance associated with the specified host, port, and authentication protocol.
public System.Net.NetworkCredential GetCredential (string host, int port, string
authenticationType);
abstract member GetCredential : string * int * string -> System.Net.NetworkCredential
override this.GetCredential : string * int * string -> System.Net.NetworkCredential

Parameters
host String String
A String that identifies the host computer.
port Int32 Int32
A Int32 that specifies the port to connect to on host .

authenticationType String String


A String that identifies the authentication scheme used when connecting to host .
Returns
NetworkCredential NetworkCredential
A NetworkCredential or, if there is no matching credential in the cache, null .
Exceptions
ArgumentNullException ArgumentNullException
host is null .
-or-
authType is null .

ArgumentException ArgumentException
authType not an accepted value.
-or-
host is equal to the empty string ("").
ArgumentOutOfRangeException ArgumentOutOfRangeException
port is less than zero.
Remarks
This method searches the CredentialCache and returns the NetworkCredential instance for the specified host, port, and
authorization type. The host , port , and authType values passed to this method are case-insensitively compared to
the values specified when the credential was added to the CredentialCache using the Add methods.
The supported values for authType are "NTLM", "Digest", "Kerberos", and "Negotiate".
CredentialCache.GetEnumerator CredentialCache.Get
Enumerator
I n this Article
Returns an enumerator that can iterate through the CredentialCache instance.

public System.Collections.IEnumerator GetEnumerator ();


abstract member GetEnumerator : unit -> System.Collections.IEnumerator
override this.GetEnumerator : unit -> System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
An IEnumerator for the CredentialCache.

Examples
The following code example uses the GetEnumerator method to return an enumerator that can iterate through the
CredentialCache instance.
public static void GetPage(string url,string userName,string password,string domainName)
{
try
{
CredentialCache myCredentialCache = new CredentialCache();
// Dummy Credentials used here.
myCredentialCache.Add(new Uri("http://microsoft.com/"),"Basic", new
NetworkCredential("user1","passwd1","domain1"));
myCredentialCache.Add(new Uri("http://msdn.com/"),"Basic", new
NetworkCredential("user2","passwd2","domain2"));

myCredentialCache.Add(new Uri(url),"Basic", new


NetworkCredential(userName,password,domainName));
// Creates a webrequest with the specified url.
WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentialCache;
IEnumerator listCredentials = myCredentialCache.GetEnumerator();

Console.WriteLine("
Displaying credentials stored in CredentialCache: ");
while(listCredentials.MoveNext())
{
Display((NetworkCredential)listCredentials.Current);
}
Console.WriteLine("
Now Displaying the same using 'foreach' : ");
// Can use foreach with CredentialCache(Since GetEnumerator function of IEnumerable has
been implemented by 'CredentialCache' class.
foreach(NetworkCredential credential in myCredentialCache)
Display(credential);
// Send the request and waits for response.
WebResponse myWebResponse = myWebRequest.GetResponse();

// Process response here.

Console.WriteLine("
Response Received.");
myWebResponse.Close();

}
catch(WebException e)
{
if (e.Response != null)
Console.WriteLine("\r
Failed to obtain a response. The following error occured : {0}",((HttpWebResponse)
(e.Response)).StatusDescription);
else
Console.WriteLine("\r
Failed to obtain a response. The following error occured : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following exception was raised : {0}",e.Message);
}
}
public static void Display(NetworkCredential credential)
{
Console.WriteLine("
Username : {0} ,Password : {1} ,Domain :
{2}",credential.UserName,credential.Password,credential.Domain);
}
CredentialCache.Remove CredentialCache.Remove
I n this Article

Overloads
Remove(Uri, String) Remove(Uri, String)
Deletes a NetworkCredential instance from the cache if it is
associated with the specified Uniform Resource Identifier (URI)
prefix and authentication protocol.

Remove(String, Int32, String) Remove(String, Int32, String)


Deletes a NetworkCredential instance from the cache if it is
associated with the specified host, port, and authentication
protocol.

Remove(Uri, String) Remove(Uri, String)


Deletes a NetworkCredential instance from the cache if it is associated with the specified Uniform Resource Identifier
(URI) prefix and authentication protocol.

public void Remove (Uri uriPrefix, string authType);


member this.Remove : Uri * string -> unit

Parameters
uriPrefix Uri Uri
A Uri that specifies the URI prefix of the resources that the credential is used for.
authType String String
The authentication scheme used by the host named in uriPrefix .
Examples
The following code example uses this method to delete a NetworkCredential instance from the cache.
// Create a webrequest with the specified url.
WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentialCache;
Console.WriteLine("
Linked CredentialCache to your request.");
// Send the request and wait for response.
WebResponse myWebResponse = myWebRequest.GetResponse();

// Process response here.

Console.Write("Response received successfully.");


// Call 'Remove' method to dispose credentials for current Uri as not required further.
myCredentialCache.Remove(myWebRequest.RequestUri,"Basic");
Console.WriteLine("
Your credentials have now been removed from the program's CredentialCache");
myWebResponse.Close();

Remarks
This method removes a NetworkCredential instance from the CredentialCache if the specified URI prefix and
authentication protocol match those associated with the credential. Multiple calls to the Remove method for the same
NetworkCredential have no effect.
If authType is null or uriPrefix is null , or no matching credential is found in the cache, this method does nothing.

Remove(String, Int32, String) Remove(String, Int32, String)


Deletes a NetworkCredential instance from the cache if it is associated with the specified host, port, and authentication
protocol.
public void Remove (string host, int port, string authenticationType);
member this.Remove : string * int * string -> unit

Parameters
host String String
A String that identifies the host computer.
port Int32 Int32
A Int32 that specifies the port to connect to on host .
authenticationType String String
A String that identifies the authentication scheme used when connecting to host .
Remarks
This method removes a NetworkCredential instance from the CredentialCache if the specified host, port, and
authentication protocol match those associated with the credential. Multiple calls to the Remove method for the same
NetworkCredential have no effect.
If authType is null or uriPrefix is null , or no matching credential is found in the cache, this method does nothing.
DecompressionMethods DecompressionMethods Enum
Represents the file compression and decompression encoding format to be used to compress the data received in
response to an HttpWebRequest.

D eclaration
[System.Flags]
public enum DecompressionMethods
type DecompressionMethods =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Fields
All All

Brotli Brotli

Deflate Deflate Use the deflate compression-decompression algorithm.

GZip GZip Use the gZip compression-decompression algorithm.

None None Do not use compression.


Dns Dns Class
Provides simple domain name resolution functionality.

D eclaration
public static class Dns
type Dns = class

I nheritance H ierarchy
Object Object

Remarks
The Dns class is a static class that retrieves information about a specific host from the Internet Domain Name System
(DNS ).

The host information from the DNS query is returned in an instance of the IPHostEntry class. If the specified host has
more than one entry in the DNS database, IPHostEntry contains multiple IP addresses and aliases.

Methods
BeginGetHostAddresses(String, AsyncCallback, Object)
BeginGetHostAddresses(String, AsyncCallback, Object)

Asynchronously returns the Internet Protocol (IP ) addresses for the specified host.

BeginGetHostByName(String, AsyncCallback, Object)


BeginGetHostByName(String, AsyncCallback, Object)

Begins an asynchronous request for IPHostEntry information about the specified DNS host name.

BeginGetHostEntry(IPAddress, AsyncCallback, Object)


BeginGetHostEntry(IPAddress, AsyncCallback, Object)

Asynchronously resolves an IP address to an IPHostEntry instance.

BeginGetHostEntry(String, AsyncCallback, Object)


BeginGetHostEntry(String, AsyncCallback, Object)

Asynchronously resolves a host name or IP address to an IPHostEntry instance.

BeginResolve(String, AsyncCallback, Object)


BeginResolve(String, AsyncCallback, Object)

Begins an asynchronous request to resolve a DNS host name or IP address to an IPAddress instance.
EndGetHostAddresses(IAsyncResult)
EndGetHostAddresses(IAsyncResult)

Ends an asynchronous request for DNS information.

EndGetHostByName(IAsyncResult)
EndGetHostByName(IAsyncResult)

Ends an asynchronous request for DNS information.

EndGetHostEntry(IAsyncResult)
EndGetHostEntry(IAsyncResult)

Ends an asynchronous request for DNS information.

EndResolve(IAsyncResult)
EndResolve(IAsyncResult)

Ends an asynchronous request for DNS information.

GetHostAddresses(String)
GetHostAddresses(String)

Returns the Internet Protocol (IP ) addresses for the specified host.

GetHostAddressesAsync(String)
GetHostAddressesAsync(String)

Returns the Internet Protocol (IP ) addresses for the specified host as an asynchronous operation.

GetHostByAddress(IPAddress)
GetHostByAddress(IPAddress)

Creates an IPHostEntry instance from the specified IPAddress.

GetHostByAddress(String)
GetHostByAddress(String)

Creates an IPHostEntry instance from an IP address.

GetHostByName(String)
GetHostByName(String)

Gets the DNS information for the specified DNS host name.
GetHostEntry(IPAddress)
GetHostEntry(IPAddress)

Resolves an IP address to an IPHostEntry instance.

GetHostEntry(String)
GetHostEntry(String)

Resolves a host name or IP address to an IPHostEntry instance.

GetHostEntryAsync(IPAddress)
GetHostEntryAsync(IPAddress)

Resolves an IP address to an IPHostEntry instance as an asynchronous operation.

GetHostEntryAsync(String)
GetHostEntryAsync(String)

Resolves a host name or IP address to an IPHostEntry instance as an asynchronous operation.

GetHostName()
GetHostName()

Gets the host name of the local computer.

Resolve(String)
Resolve(String)

Resolves a DNS host name or IP address to an IPHostEntry instance.


Dns.BeginGetHostAddresses Dns.BeginGetHostAddresses
I n this Article
Asynchronously returns the Internet Protocol (IP ) addresses for the specified host.
public static IAsyncResult BeginGetHostAddresses (string hostNameOrAddress, AsyncCallback
requestCallback, object state);
static member BeginGetHostAddresses : string * AsyncCallback * obj -> IAsyncResult

Parameters
hostNameOrAddress String String
The host name or IP address to resolve.
requestCallback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
state Object Object
A user-defined object that contains information about the operation. This object is passed to the requestCallback
delegate when the operation is complete.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that references the asynchronous request.
Exceptions
ArgumentNullException ArgumentNullException
hostNameOrAddress is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostNameOrAddress is greater than 255 characters.
SocketException SocketException
An error is encountered when resolving hostNameOrAddress .
ArgumentException ArgumentException
hostNameOrAddress is an invalid IP address.

Remarks
The BeginGetHostAddresses method asynchronously queries a DNS server for the IP addresses that are associated
with a host name. If hostNameOrAddress is an IP address, this address is returned without querying the DNS server.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
If an empty string is passed as the hostNameOrAddress argument, then this method returns the IPv4 and IPv6
addresses of the local host.
The asynchronous BeginGetHostAddresses operation must be completed by calling the EndGetHostAddresses
method. Typically, the method is invoked by the requestCallback delegate.
This method does not block until the operation is complete. To block until the operation is complete, use the
GetHostAddresses method.
For more information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously
Dns.BeginGetHostByName Dns.BeginGetHostByName
I n this Article
Begins an asynchronous request for IPHostEntry information about the specified DNS host name.
[System.Obsolete("Use BeginGetHostEntry instead")]
[System.Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry
instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("BeginGetHostByName is obsoleted for this type, please use BeginGetHostEntry
instead. https://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginGetHostByName (string hostName, AsyncCallback requestCallback,
object stateObject);
static member BeginGetHostByName : string * AsyncCallback * obj -> IAsyncResult

Parameters
hostName String String
The DNS name of the host.
requestCallback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
stateObject Object Object
A user-defined object that contains information about the operation. This object is passed to the requestCallback
delegate when the operation is complete.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that references the asynchronous request.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
hostName is null .
SocketException SocketException
An error was encountered executing the DNS query.

Remarks
The asynchronous BeginGetHostByName operation must be completed by calling the EndGetHostByName method.
Typically, the method is invoked by the requestCallback delegate.
This method does not block until the operation is complete. To block until the operation is complete, use the
GetHostByName method.
For detailed information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
See Asynchronous Programming Overview
Also
Dns.BeginGetHostEntry Dns.BeginGetHostEntry
I n this Article

Overloads
BeginGetHostEntry(IPAddress, AsyncCallback, Object) Begin
GetHostEntry(IPAddress, AsyncCallback, Object) Asynchronously resolves an IP address to an IPHostEntry
instance.

BeginGetHostEntry(String, AsyncCallback, Object) BeginGet


HostEntry(String, AsyncCallback, Object) Asynchronously resolves a host name or IP address to an
IPHostEntry instance.

BeginGetHostEntry(IPAddress, AsyncCallback, Object)


BeginGetHostEntry(IPAddress, AsyncCallback, Object)
Asynchronously resolves an IP address to an IPHostEntry instance.
public static IAsyncResult BeginGetHostEntry (System.Net.IPAddress address, AsyncCallback
requestCallback, object stateObject);
static member BeginGetHostEntry : System.Net.IPAddress * AsyncCallback * obj -> IAsyncResult

Parameters
address IPAddress IPAddress
The IP address to resolve.
requestCallback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
stateObject Object Object
A user-defined object that contains information about the operation. This object is passed to the requestCallback
delegate when the operation is complete.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that references the asynchronous request.
Exceptions
ArgumentNullException ArgumentNullException
address is null .

SocketException SocketException
An error is encountered when resolving address .
ArgumentException ArgumentException
address is an invalid IP address.
Examples
The following code example uses the BeginGetHostEntry method to resolve an IP address to an IPHostEntry instance.
// Signals when the resolve has finished.
public static ManualResetEvent GetHostEntryFinished =
new ManualResetEvent(false);

// Define the state object for the callback.


// Use hostName to correlate calls with the proper result.
public class ResolveState
{
string hostName;
IPHostEntry resolvedIPs;

public ResolveState(string host)


{
hostName = host;
}

public IPHostEntry IPs


{
get { return resolvedIPs; }
set { resolvedIPs = value; }
}

public string host


{
get { return hostName; }
set { hostName = value; }
}
}

// Record the IPs in the state object for later use.


public static void GetHostEntryCallback(IAsyncResult ar)
{
ResolveState ioContext = (ResolveState)ar.AsyncState;
ioContext.IPs = Dns.EndGetHostEntry(ar);
GetHostEntryFinished.Set();
}

// Determine the Internet Protocol (IP) addresses for


// this host asynchronously.
public static void DoGetHostEntryAsync(string hostname)
{
GetHostEntryFinished.Reset();
ResolveState ioContext= new ResolveState(hostname);

Dns.BeginGetHostEntry(ioContext.host,
new AsyncCallback(GetHostEntryCallback), ioContext);

// Wait here until the resolve completes (the callback


// calls .Set())
GetHostEntryFinished.WaitOne();

Console.WriteLine("EndGetHostEntry({0}) returns:", ioContext.host);

foreach (IPAddress address in ioContext.IPs.AddressList)


{
Console.WriteLine($" {address}");
}
}

Remarks
The BeginGetHostEntry method asynchronously queries a DNS server for the IP addresses and aliases associated with
an IP address.
Note This member emits trace information when you enable network tracing in your application. For more
information, see Network Tracing in the .NET Framework.
The asynchronous BeginGetHostEntry operation must be completed by calling the EndGetHostEntry method. Typically,
the method is invoked by the requestCallback delegate.
This method does not block until the operation is complete. To block until the operation is complete, use the
GetHostEntry method.
For detailed information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously

BeginGetHostEntry(String, AsyncCallback, Object)


BeginGetHostEntry(String, AsyncCallback, Object)
Asynchronously resolves a host name or IP address to an IPHostEntry instance.
public static IAsyncResult BeginGetHostEntry (string hostNameOrAddress, AsyncCallback
requestCallback, object stateObject);
static member BeginGetHostEntry : string * AsyncCallback * obj -> IAsyncResult

Parameters
hostNameOrAddress String String
The host name or IP address to resolve.
requestCallback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
stateObject Object Object
A user-defined object that contains information about the operation. This object is passed to the requestCallback
delegate when the operation is complete.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that references the asynchronous request.
Exceptions
ArgumentNullException ArgumentNullException
hostNameOrAddress is null .

ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostNameOrAddress is greater than 255 characters.
SocketException SocketException
An error is encountered when resolving hostNameOrAddress .
ArgumentException ArgumentException
hostNameOrAddress is an invalid IP address.
Examples
The following code example uses the BeginGetHostEntry method to resolve an IP address to an IPHostEntry instance.

// Signals when the resolve has finished.


public static ManualResetEvent GetHostEntryFinished =
new ManualResetEvent(false);

// Define the state object for the callback.


// Use hostName to correlate calls with the proper result.
public class ResolveState
{
string hostName;
IPHostEntry resolvedIPs;

public ResolveState(string host)


{
hostName = host;
}

public IPHostEntry IPs


{
get { return resolvedIPs; }
set { resolvedIPs = value; }
}

public string host


{
get { return hostName; }
set { hostName = value; }
}
}

// Record the IPs in the state object for later use.


public static void GetHostEntryCallback(IAsyncResult ar)
{
ResolveState ioContext = (ResolveState)ar.AsyncState;
ioContext.IPs = Dns.EndGetHostEntry(ar);
GetHostEntryFinished.Set();
}

// Determine the Internet Protocol (IP) addresses for


// this host asynchronously.
public static void DoGetHostEntryAsync(string hostname)
{
GetHostEntryFinished.Reset();
ResolveState ioContext= new ResolveState(hostname);

Dns.BeginGetHostEntry(ioContext.host,
new AsyncCallback(GetHostEntryCallback), ioContext);

// Wait here until the resolve completes (the callback


// calls .Set())
GetHostEntryFinished.WaitOne();

Console.WriteLine("EndGetHostEntry({0}) returns:", ioContext.host);

foreach (IPAddress address in ioContext.IPs.AddressList)


{
Console.WriteLine($" {address}");
}
}

Remarks
The BeginGetHostEntry method queries a DNS server for the IP address that is associated with a host name or IP
address.
Note This member emits trace information when you enable network tracing in your application. For more
information, see Network Tracing in the .NET Framework.
The asynchronous BeginGetHostEntry operation must be completed by calling the EndGetHostEntry method. Typically,
the method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use the
GetHostEntry method.
For detailed information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously.
Dns.BeginResolve Dns.BeginResolve
I n this Article
Begins an asynchronous request to resolve a DNS host name or IP address to an IPAddress instance.
[System.Obsolete("Use BeginGetHostEntry instead")]
[System.Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("BeginResolve is obsoleted for this type, please use BeginGetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static IAsyncResult BeginResolve (string hostName, AsyncCallback requestCallback, object
stateObject);
static member BeginResolve : string * AsyncCallback * obj -> IAsyncResult

Parameters
hostName String String
The DNS name of the host.
requestCallback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
stateObject Object Object
A user-defined object that contains information about the operation. This object is passed to the requestCallback
delegate when the operation is complete.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that references the asynchronous request.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
hostName is null .
SocketException SocketException
The caller does not have permission to access DNS information.

Examples
The following example uses BeginResolve to resolve a DNS host name to an IPAddress.
class DnsBeginGetHostByName
{
public static System.Threading.ManualResetEvent allDone = null;

class RequestState
{
public IPHostEntry host;
public RequestState()
{
host = null;
}
}

public static void Main()


{
allDone = new ManualResetEvent(false);
// Create an instance of the RequestState class.
RequestState myRequestState = new RequestState();

// Begin an asynchronous request for information like host name, IP addresses, or


// aliases for specified the specified URI.
IAsyncResult asyncResult = Dns.BeginResolve("www.contoso.com", new AsyncCallback(RespCallback),
myRequestState );

// Wait until asynchronous call completes.


allDone.WaitOne();
Console.WriteLine("Host name : " + myRequestState.host.HostName);
Console.WriteLine("
IP address list : ");
for(int index=0; index < myRequestState.host.AddressList.Length; index++)
{
Console.WriteLine(myRequestState.host.AddressList[index]);
}
Console.WriteLine("
Aliases : ");
for(int index=0; index < myRequestState.host.Aliases.Length; index++)
{
Console.WriteLine(myRequestState.host.Aliases[index]);
}
}

private static void RespCallback(IAsyncResult ar)


{
try
{
// Convert the IAsyncResult object to a RequestState object.
RequestState tempRequestState = (RequestState)ar.AsyncState;
// End the asynchronous request.
tempRequestState.host = Dns.EndResolve(ar);
allDone.Set();
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
}

Remarks
The asynchronous BeginResolve operation must be completed by calling the EndResolve method. Typically, the
method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use the Resolve
method.
For more information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
See Asynchronous Programming Overview
Also
Dns.EndGetHostAddresses Dns.EndGetHostAddresses
I n this Article
Ends an asynchronous request for DNS information.
public static System.Net.IPAddress[] EndGetHostAddresses (IAsyncResult asyncResult);
static member EndGetHostAddresses : IAsyncResult -> System.Net.IPAddress[]

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult instance returned by a call to the BeginGetHostAddresses(String, AsyncCallback, Object) method.
Returns
IPAddress[]
An array of type IPAddress that holds the IP addresses for the host specified by the hostNameOrAddress parameter of
BeginGetHostAddresses(String, AsyncCallback, Object).

Remarks
The BeginGetHostAddresses method queries a DNS server for the IP addresses associated with a host name. If
hostNameOrAddress is an IP address, this address is returned without querying the DNS server.

If an empty string is passed as the hostNameOrAddress argument, then this method returns the IPv4 and IPv6
addresses of the local host.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.EndGetHostByName Dns.EndGetHostByName
I n this Article
Ends an asynchronous request for DNS information.
[System.Obsolete("Use EndGetHostEntry instead")]
[System.Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("EndGetHostByName is obsoleted for this type, please use EndGetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.IPHostEntry EndGetHostByName (IAsyncResult asyncResult);
static member EndGetHostByName : IAsyncResult -> System.Net.IPHostEntry

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult instance that is returned by a call to the BeginGetHostByName(String, AsyncCallback, Object)
method.
Returns
IPHostEntry IPHostEntry
An IPHostEntry object that contains DNS information about a host.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .

Remarks
This method blocks until the operation is complete.
To perform this operation synchronously, use the GetHostByName method.
If the Ipv6Element.Enabled property is set to true , the Aliases property of the IPHostEntry instance returned is not
populated by this method and will always be empty.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
See Asynchronous Programming Overview
Also
Dns.EndGetHostEntry Dns.EndGetHostEntry
I n this Article
Ends an asynchronous request for DNS information.
public static System.Net.IPHostEntry EndGetHostEntry (IAsyncResult asyncResult);
static member EndGetHostEntry : IAsyncResult -> System.Net.IPHostEntry

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult instance returned by a call to an BeginGetHostEntry method.
Returns
IPHostEntry IPHostEntry
An IPHostEntry instance that contains address information about the host.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .

Remarks
This method blocks until the operation is complete.
The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
To perform this operation synchronously, use a GetHostEntry method.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.EndResolve Dns.EndResolve
I n this Article
Ends an asynchronous request for DNS information.
[System.Obsolete("Use EndGetHostEntry instead")]
[System.Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("EndResolve is obsoleted for this type, please use EndGetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.IPHostEntry EndResolve (IAsyncResult asyncResult);
static member EndResolve : IAsyncResult -> System.Net.IPHostEntry

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult instance that is returned by a call to the BeginResolve(String, AsyncCallback, Object) method.
Returns
IPHostEntry IPHostEntry
An IPHostEntry object that contains DNS information about a host.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .

Examples
The following example ends an asynchronous request for DNS host information.
class DnsBeginGetHostByName
{
public static System.Threading.ManualResetEvent allDone = null;

class RequestState
{
public IPHostEntry host;
public RequestState()
{
host = null;
}
}

public static void Main()


{
allDone = new ManualResetEvent(false);
// Create an instance of the RequestState class.
RequestState myRequestState = new RequestState();

// Begin an asynchronous request for information like host name, IP addresses, or


// aliases for specified the specified URI.
IAsyncResult asyncResult = Dns.BeginResolve("www.contoso.com", new AsyncCallback(RespCallback),
myRequestState );

// Wait until asynchronous call completes.


allDone.WaitOne();
allDone.WaitOne();
Console.WriteLine("Host name : " + myRequestState.host.HostName);
Console.WriteLine("
IP address list : ");
for(int index=0; index < myRequestState.host.AddressList.Length; index++)
{
Console.WriteLine(myRequestState.host.AddressList[index]);
}
Console.WriteLine("
Aliases : ");
for(int index=0; index < myRequestState.host.Aliases.Length; index++)
{
Console.WriteLine(myRequestState.host.Aliases[index]);
}
}

private static void RespCallback(IAsyncResult ar)


{
try
{
// Convert the IAsyncResult object to a RequestState object.
RequestState tempRequestState = (RequestState)ar.AsyncState;
// End the asynchronous request.
tempRequestState.host = Dns.EndResolve(ar);
allDone.Set();
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
}

Remarks
This method blocks until the operation is complete.
If the Ipv6Element.Enabled is set to true , the Aliases property of the IPHostEntry instance returned is not populated
by this method and will always be empty.
To perform this operation synchronously, use the Resolve method.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
See Asynchronous Programming Overview
Also
Dns.GetHostAddresses Dns.GetHostAddresses
I n this Article
Returns the Internet Protocol (IP ) addresses for the specified host.
public static System.Net.IPAddress[] GetHostAddresses (string hostNameOrAddress);
static member GetHostAddresses : string -> System.Net.IPAddress[]

Parameters
hostNameOrAddress String String
The host name or IP address to resolve.
Returns
IPAddress[]
An array of type IPAddress that holds the IP addresses for the host that is specified by the hostNameOrAddress
parameter.
Exceptions
ArgumentNullException ArgumentNullException
hostNameOrAddress is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostNameOrAddress is greater than 255 characters.
SocketException SocketException
An error is encountered when resolving hostNameOrAddress .
ArgumentException ArgumentException
hostNameOrAddress is an invalid IP address.

Examples
The following code example uses the GetHostAddresses method to resolve an IP address to an array of type
IPAddress.
public static void DoGetHostAddresses(string hostname)
{
IPAddress[] addresses = Dns.GetHostAddresses(hostname);

Console.WriteLine($"GetHostAddresses({hostname}) returns:");

foreach (IPAddress address in addresses)


{
Console.WriteLine($" {address}");
}
}

Remarks
The GetHostAddresses method queries the DNS subsystem for the IP addresses associated with a host name. If
hostNameOrAddress is an IP address, this address is returned without querying the DNS server.
If an empty string is passed as the hostNameOrAddress argument, then this method returns the IPv4 and IPv6
addresses of the local host.
IPv6 addresses are filtered from the results of the GetHostAddresses method if the local computer does not have IPv6
installed. As a result, it is possible to get back an empty IPAddress instance if only IPv6 results were available for the
hostNameOrAddress parameter.

This method is implemented using the underlying operating system's name resolution APIs (such as the Win32 API
getaddrinfo on Windows, and equivalent APIs on other platforms). If a host is described in the hosts file, the IP
address or addresses there will be returned without querying the DNS server.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.GetHostAddressesAsync Dns.GetHostAddresses
Async
I n this Article
Returns the Internet Protocol (IP ) addresses for the specified host as an asynchronous operation.

public static System.Threading.Tasks.Task<System.Net.IPAddress[]> GetHostAddressesAsync (string


hostNameOrAddress);
static member GetHostAddressesAsync : string -> System.Threading.Tasks.Task<System.Net.IPAddress[]>

Parameters
hostNameOrAddress String String
The host name or IP address to resolve.
Returns
Task<IPAddress[]>
The task object representing the asynchronous operation. The Result property on the task object returns an array of
type IPAddress that holds the IP addresses for the host that is specified by the hostNameOrAddress parameter.
Exceptions
ArgumentNullException ArgumentNullException
hostNameOrAddress is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostNameOrAddress is greater than 255 characters.
SocketException SocketException
An error is encountered when resolving hostNameOrAddress .
ArgumentException ArgumentException
hostNameOrAddress is an invalid IP address.

Remarks
This operation will not block. The returned Task<TResult> object will complete after the hostNameOrAddress has been
resolved.
This method queries a DNS server for the IP addresses associated with a host name. If hostNameOrAddress is an IP
address, this address is returned without querying the DNS server.
Dns.GetHostByAddress Dns.GetHostByAddress
I n this Article

Overloads
GetHostByAddress(IPAddress) GetHostByAddress(IPAddress)
Creates an IPHostEntry instance from the specified IPAddress.

GetHostByAddress(String) GetHostByAddress(String)
Creates an IPHostEntry instance from an IP address.

GetHostByAddress(IPAddress) GetHostByAddress(IPAddress)
Creates an IPHostEntry instance from the specified IPAddress.
[System.Obsolete("Use GetHostEntry instead")]
[System.Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.IPHostEntry GetHostByAddress (System.Net.IPAddress address);
static member GetHostByAddress : System.Net.IPAddress -> System.Net.IPHostEntry

Parameters
address IPAddress IPAddress
An IPAddress.
Returns
IPHostEntry IPHostEntry
An IPHostEntry instance.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
address is null .
SocketException SocketException
An error is encountered when resolving address .
Examples
The following example creates a IPHostEntry from an IPAddress.
try
{
IPAddress hostIPAddress = IPAddress.Parse(IpAddressString);
IPHostEntry hostInfo = Dns.GetHostByAddress(hostIPAddress);
// Get the IP address list that resolves to the host names contained in
// the Alias property.
IPAddress[] address = hostInfo.AddressList;
// Get the alias names of the addresses in the IP address list.
String[] alias = hostInfo.Aliases;

Console.WriteLine("Host name : " + hostInfo.HostName);


Console.WriteLine("
Aliases :");
for(int index=0; index < alias.Length; index++) {
Console.WriteLine(alias[index]);
}
Console.WriteLine("
IP address list : ");
for(int index=0; index < address.Length; index++) {
Console.WriteLine(address[index]);
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(FormatException e)
{
Console.WriteLine("FormatException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

Remarks
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.

GetHostByAddress(String) GetHostByAddress(String)
Creates an IPHostEntry instance from an IP address.
[System.Obsolete("Use GetHostEntry instead")]
[System.Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("GetHostByAddress is obsoleted for this type, please use GetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.IPHostEntry GetHostByAddress (string address);
static member GetHostByAddress : string -> System.Net.IPHostEntry

Parameters
address String String
An IP address.
Returns
IPHostEntry IPHostEntry
An IPHostEntry instance.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
address is null .
SocketException SocketException
An error is encountered when resolving address .
FormatException FormatException
address is not a valid IP address.
Remarks
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.GetHostByName Dns.GetHostByName
I n this Article
Gets the DNS information for the specified DNS host name.
[System.Obsolete("Use GetHostEntry instead")]
[System.Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("GetHostByName is obsoleted for this type, please use GetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.IPHostEntry GetHostByName (string hostName);
static member GetHostByName : string -> System.Net.IPHostEntry

Parameters
hostName String String
The DNS name of the host.
Returns
IPHostEntry IPHostEntry
An IPHostEntry object that contains host information for the address specified in hostName .
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
hostName is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostName is greater than 255 characters.
SocketException SocketException
An error is encountered when resolving hostName .

Examples
The following example uses the GetHostByName method to get the DNS information for the specified DNS host
name.
try
{
IPHostEntry hostInfo = Dns.GetHostByName(hostName);
// Get the IP address list that resolves to the host names contained in the
// Alias property.
IPAddress[] address = hostInfo.AddressList;
// Get the alias names of the addresses in the IP address list.
String[] alias = hostInfo.Aliases;

Console.WriteLine("Host name : " + hostInfo.HostName);


Console.WriteLine("
Aliases : ");
for(int index=0; index < alias.Length; index++) {
Console.WriteLine(alias[index]);
}
Console.WriteLine("
IP address list : ");
for(int index=0; index < address.Length; index++) {
Console.WriteLine(address[index]);
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

Remarks
The GetHostByName method queries the Internet DNS server for host information. If you pass an empty string as the
host name, this method retrieves the standard host name for the local computer.
For asynchronous access to DNS information, use the BeginGetHostByName and EndGetHostByName methods.
If the Ipv6Element.Enabled property is set to true , the Aliases property of the IPHostEntry instance returned is not
populated by this method and will always be empty.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.GetHostEntry Dns.GetHostEntry
I n this Article

Overloads
GetHostEntry(IPAddress) GetHostEntry(IPAddress)
Resolves an IP address to an IPHostEntry instance.

GetHostEntry(String) GetHostEntry(String)
Resolves a host name or IP address to an IPHostEntry
instance.

GetHostEntry(IPAddress) GetHostEntry(IPAddress)
Resolves an IP address to an IPHostEntry instance.
public static System.Net.IPHostEntry GetHostEntry (System.Net.IPAddress address);
static member GetHostEntry : System.Net.IPAddress -> System.Net.IPHostEntry

Parameters
address IPAddress IPAddress
An IP address.
Returns
IPHostEntry IPHostEntry
An IPHostEntry instance that contains address information about the host specified in address .
Exceptions
ArgumentNullException ArgumentNullException
address is null .
SocketException SocketException
An error is encountered when resolving address .
ArgumentException ArgumentException
address is an invalid IP address.
Examples
The following code example uses the GetHostEntry method to resolve an IP address to an IPHostEntry instance.
public static void DoGetHostEntry(IPAddress address)
{
IPHostEntry host = Dns.GetHostEntry(address);

Console.WriteLine($"GetHostEntry({address}) returns HostName: {host.HostName}");


}

Remarks
The GetHostEntry method queries a DNS server for the IP addresses and aliases associated with an IP address.
IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6
installed. As a result, it is possible to get back an empty IPHostEntry instance if only IPv6 results were available for the
address parameter.

The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.

GetHostEntry(String) GetHostEntry(String)
Resolves a host name or IP address to an IPHostEntry instance.
public static System.Net.IPHostEntry GetHostEntry (string hostNameOrAddress);
static member GetHostEntry : string -> System.Net.IPHostEntry

Parameters
hostNameOrAddress String String
The host name or IP address to resolve.
Returns
IPHostEntry IPHostEntry
An IPHostEntry instance that contains address information about the host specified in hostNameOrAddress .

Exceptions
ArgumentNullException ArgumentNullException
The hostNameOrAddress parameter is null .

ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostNameOrAddress parameter is greater than 255 characters.

SocketException SocketException
An error was encountered when resolving the hostNameOrAddress parameter.

ArgumentException ArgumentException
The hostNameOrAddress parameter is an invalid IP address.
Examples
The following example uses the GetHostEntry method to resolve an IP address to an IPHostEntry instance.
public static void DoGetHostEntry(string hostname)
{
IPHostEntry host = Dns.GetHostEntry(hostname);

Console.WriteLine($"GetHostEntry({hostname}) returns:");

foreach (IPAddress address in host.AddressList)


{
Console.WriteLine($" {address}");
}
}

Remarks
The GetHostEntry method queries a DNS server for the IP address that is associated with a host name or IP address.
If an empty string is passed as the hostNameOrAddress argument, then this method returns the IPv4 and IPv6
addresses of the local host.
If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows
Sockets error WSAHOST_NOT_FOUND ). This exception can be returned if the DNS server does not respond. This
exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s)
being queried.
The ArgumentException exception is also returned if the hostNameOrAddress parameter contains Any or IPv6Any.

The GetHostEntry method assumes that if an IP literal string is passed in the hostNameOrAddress parameter that the
application wants an IPHostEntry instance returned with all of the properties set. These properties include the
AddressList, Aliases, and HostName. As a result, the implementation of the GetHostEntry method exhibits the
following behavior when an IP string literal is passed:
1. The method tries to parse the address. If the hostNameOrAddress parameter contains a legal IP string literal, then the
first phase succeeds.
2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as
the HostName property.
3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name
and set as the AddressList property.
For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4
address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception
(there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address).

For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR ) record for an IPv6
address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN ) host name in the
HostName property.
The GetHostAddresses method has different behavior with respect to IP literals. If step #1 above succeeds (it
successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a
reverse lookup.
IPv6 addresses are filtered from the results of the GetHostEntry method if the local computer does not have IPv6
installed. As a result, it is possible to get back an empty IPHostEntry instance if only IPv6 results where available for the
hostNameOrAddress .parameter.

The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.GetHostEntryAsync Dns.GetHostEntryAsync
I n this Article

Overloads
GetHostEntryAsync(IPAddress) GetHostEntryAsync(IPAddress)
Resolves an IP address to an IPHostEntry instance as an
asynchronous operation.

GetHostEntryAsync(String) GetHostEntryAsync(String)
Resolves a host name or IP address to an IPHostEntry instance
as an asynchronous operation.

GetHostEntryAsync(IPAddress) GetHostEntryAsync(IPAddress)
Resolves an IP address to an IPHostEntry instance as an asynchronous operation.
public static System.Threading.Tasks.Task<System.Net.IPHostEntry> GetHostEntryAsync
(System.Net.IPAddress address);
static member GetHostEntryAsync : System.Net.IPAddress ->
System.Threading.Tasks.Task<System.Net.IPHostEntry>

Parameters
address IPAddress IPAddress
An IP address.
Returns
Task<IPHostEntry>
The task object representing the asynchronous operation. The Result property on the task object returns an
IPHostEntry instance that contains address information about the host specified in address .
Exceptions
ArgumentNullException ArgumentNullException
address is null .
SocketException SocketException
An error is encountered when resolving address .
ArgumentException ArgumentException
address is an invalid IP address.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the address has been resolved.
This method queries a DNS server for the IP addresses and aliases associated with an IP address.
IPv6 addresses are filtered from the results of this method if the local computer does not have IPv6 installed. As a
result, it is possible to get back an empty IPHostEntry instance if only IPv6 results where available for the address
parameter.
The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.

GetHostEntryAsync(String) GetHostEntryAsync(String)
Resolves a host name or IP address to an IPHostEntry instance as an asynchronous operation.
public static System.Threading.Tasks.Task<System.Net.IPHostEntry> GetHostEntryAsync (string
hostNameOrAddress);
static member GetHostEntryAsync : string -> System.Threading.Tasks.Task<System.Net.IPHostEntry>

Parameters
hostNameOrAddress String String
The host name or IP address to resolve.
Returns
Task<IPHostEntry>
The task object representing the asynchronous operation. The Result property on the task object returns an
IPHostEntry instance that contains address information about the host specified in hostNameOrAddress .

Exceptions
ArgumentNullException ArgumentNullException
The hostNameOrAddress parameter is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostNameOrAddress parameter is greater than 255 characters.
SocketException SocketException
An error was encountered when resolving the hostNameOrAddress parameter.

ArgumentException ArgumentException
The hostNameOrAddress parameter is an invalid IP address.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the hostNameOrAddress has been
resolved.
This method queries a DNS server for the IP address that is associated with a host name or IP address.
If an empty string is passed as the hostNameOrAddress argument, then this method returns the IPv4 and IPv6
addresses of the local host.
If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows
Sockets error WSAHOST_NOT_FOUND ). This exception can be returned if the DNS server does not respond. This
exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s)
being queried.
The ArgumentException exception is also returned if the hostNameOrAddress parameter contains Any or IPv6Any.
This method assumes that if an IP literal string is passed in the hostNameOrAddress parameter that the application
wants an IPHostEntry instance returned with all of the properties set. These properties include the AddressList, Aliases,
and HostName. As a result, the implementation of this method exhibits the following behavior when an IP string literal
is passed:
1. The method tries to parse the address. If the hostNameOrAddress parameter contains a legal IP string literal, then the
first phase succeeds.
2. A reverse lookup using the IP address of the IP string literal is attempted to obtain the host name. This result is set as
the HostName property.
3. The host name from this reverse lookup is used again to obtain all the possible IP addresses associated with the name
and set as the AddressList property.
For an IPv4 string literal, all three steps above may succeed. But it is possible for a stale DNS record for an IPv4
address that actually belongs to a different host to be returned. This may cause step #3 to fail and throw an exception
(there is a DNS PTR record for the IPv4 address, but no DNS A record for the IPv4 address).

For IPv6, step #2 above may fail, since most IPv6 deployments do not register the reverse (PTR ) record for an IPv6
address. So this method may return the string IPv6 literal as the fully-qualified domain (FQDN ) host name in the
HostName property.
The GetHostAddresses method has different behavior with respect to IP literals. If step #1 above succeeds (it
successfully parses as an IP address), that address is immediately returned as the result. There is no attempt at a
reverse lookup.
IPv6 addresses are filtered from the results of this method if the local computer does not have IPv6 installed. As a
result, it is possible to get back an empty IPHostEntry instance if only IPv6 results where available for the
hostNameOrAddress .parameter.

The Aliases property of the IPHostEntry instance returned is not populated by this method and will always be empty.
This method is implemented using the underlying operating system's name resolution APIs (such as the Win32 API
getaddrinfo on Windows, and equivalent APIs on other platforms). If a host is described in the hosts file, the IP
address or addresses there will be returned without querying the DNS server.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
Dns.GetHostName Dns.GetHostName
I n this Article
Gets the host name of the local computer.
public static string GetHostName ();
static member GetHostName : unit -> string

Returns
String String
A string that contains the DNS host name of the local computer.
Exceptions
SocketException SocketException
An error is encountered when resolving the local host name.

Examples
The following example uses the GetHostName method to obtain the host name of the local computer.
public void DisplayLocalHostName()
{
try {
// Get the local computer host name.
String hostName = Dns.GetHostName();
Console.WriteLine("Computer name :" + hostName);
}
catch(SocketException e) {
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
Dns.Resolve Dns.Resolve
I n this Article
Resolves a DNS host name or IP address to an IPHostEntry instance.
[System.Obsolete("Use GetHostEntry instead")]
[System.Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("Resolve is obsoleted for this type, please use GetHostEntry instead.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.IPHostEntry Resolve (string hostName);
static member Resolve : string -> System.Net.IPHostEntry

Parameters
hostName String String
A DNS -style host name or IP address.
Returns
IPHostEntry IPHostEntry
An IPHostEntry instance that contains address information about the host specified in hostName .
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
ArgumentNullException ArgumentNullException
hostName is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of hostName is greater than 255 characters.
SocketException SocketException
An error is encountered when resolving hostName .

Examples
The following example uses the Resolve method to resolve an IP address to an IPHostEntry instance.
try {
IPHostEntry hostInfo = Dns.Resolve(hostString);
// Get the IP address list that resolves to the host names contained in the
// Alias property.
IPAddress[] address = hostInfo.AddressList;
// Get the alias names of the addresses in the IP address list.
String[] alias = hostInfo.Aliases;

Console.WriteLine("Host name : " + hostInfo.HostName);


Console.WriteLine("
Aliases : ");
for(int index=0; index < alias.Length; index++) {
Console.WriteLine(alias[index]);
}
Console.WriteLine("
IP Address list :");
for(int index=0; index < address.Length; index++) {
Console.WriteLine(address[index]);
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(NullReferenceException e)
{
Console.WriteLine("NullReferenceException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

Remarks
The Resolve method queries a DNS server for the IP address associated with a host name or IP address.
When hostName is a DNS -style host name associated with multiple IP addresses, only the first IP address that resolves
to that host name is returned.
If the Ipv6Element.Enabled property is set to true , the Aliases property of the IPHostEntry instance returned is not
populated by this method and will always be empty.
Note

This member emits trace information when you enable network tracing in your application. For more information, see
Network Tracing in the .NET Framework.
DnsEndPoint DnsEndPoint Class
Represents a network endpoint as a host name or a string representation of an IP address and a port number.

D eclaration
public class DnsEndPoint : System.Net.EndPoint
type DnsEndPoint = class
inherit EndPoint

I nheritance H ierarchy
Object Object
EndPoint EndPoint

Remarks
The DnsEndPoint class contains a host name or an IP address and remote port information needed by an application
to connect to a service on a host. By combining the host name or IP address and port number of a service, the
DnsEndPoint class forms a connection point to a service.

Constructors
DnsEndPoint(String, Int32)
DnsEndPoint(String, Int32)

Initializes a new instance of the DnsEndPoint class with the host name or string representation of an IP address
and a port number.

DnsEndPoint(String, Int32, AddressFamily)


DnsEndPoint(String, Int32, AddressFamily)

Initializes a new instance of the DnsEndPoint class with the host name or string representation of an IP address, a
port number, and an address family.

Properties
AddressFamily
AddressFamily

Gets the Internet Protocol (IP ) address family.

Host
Host

Gets the host name or string representation of the Internet Protocol (IP ) address of the host.

Port
Port
Gets the port number of the DnsEndPoint.

Methods
Equals(Object)
Equals(Object)

Compares two DnsEndPoint objects.

GetHashCode()
GetHashCode()

Returns a hash value for a DnsEndPoint.

ToString()
ToString()

Returns the host name or string representation of the IP address and port number of the DnsEndPoint.
DnsEndPoint.AddressFamily DnsEndPoint.AddressFamily
I n this Article
Gets the Internet Protocol (IP ) address family.
public override System.Net.Sockets.AddressFamily AddressFamily { get; }
member this.AddressFamily : System.Net.Sockets.AddressFamily

Returns
AddressFamily AddressFamily
One of the AddressFamily values.

Remarks
The AddressFamily property indicates the address family for an instance of the DnsEndPoint class.
DnsEndPoint DnsEndPoint
I n this Article

Overloads
DnsEndPoint(String, Int32) DnsEndPoint(String, Int32)
Initializes a new instance of the DnsEndPoint class with the
host name or string representation of an IP address and a
port number.

DnsEndPoint(String, Int32, AddressFamily) DnsEndPoint(


String, Int32, AddressFamily) Initializes a new instance of the DnsEndPoint class with the
host name or string representation of an IP address, a port
number, and an address family.

DnsEndPoint(String, Int32) DnsEndPoint(String, Int32)


Initializes a new instance of the DnsEndPoint class with the host name or string representation of an IP address and a
port number.
public DnsEndPoint (string host, int port);
new System.Net.DnsEndPoint : string * int -> System.Net.DnsEndPoint

Parameters
host String String
The host name or a string representation of the IP address.
port Int32 Int32
The port number associated with the address, or 0 to specify any available port. port is in host order.
Exceptions
ArgumentException ArgumentException
The host parameter contains an empty string.
ArgumentNullException ArgumentNullException
The host parameter is a null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
port is less than MinPort.
-or-
port is greater than MaxPort.
Remarks
The DnsEndPoint(String, Int32) constructor can be used to initialize a DnsEndPoint class using either a host name or a
string that represents an IP address and a port. This constructor sets the AddressFamily property to Unknown.
When using this constructor with a host name rather than a string representation of an IP address, the address family
of the DnsEndPoint will remain Unknown even after use. The AddressFamily property of any Socket that is created by
calls to the ConnectAsync method will be the address family of the first address to which a connection can be
successfully established (not necessarily the first address to be resolved).

DnsEndPoint(String, Int32, AddressFamily) DnsEndPoint(String,


Int32, AddressFamily)
Initializes a new instance of the DnsEndPoint class with the host name or string representation of an IP address, a port
number, and an address family.
public DnsEndPoint (string host, int port, System.Net.Sockets.AddressFamily addressFamily);
new System.Net.DnsEndPoint : string * int * System.Net.Sockets.AddressFamily ->
System.Net.DnsEndPoint

Parameters
host String String
The host name or a string representation of the IP address.
port Int32 Int32
The port number associated with the address, or 0 to specify any available port. port is in host order.

addressFamily AddressFamily AddressFamily


One of the AddressFamily values.
Exceptions
ArgumentException ArgumentException
The host parameter contains an empty string.
-or-
addressFamily is Unknown.

ArgumentNullException ArgumentNullException
The host parameter is a null .

ArgumentOutOfRangeException ArgumentOutOfRangeException
port is less than MinPort.
-or-
port is greater than MaxPort.
Remarks
The DnsEndPoint(String, Int32, AddressFamily) constructor can be used to initialize a DnsEndPoint class using either a
host name or a string that represents an IP address, a port, and an address family.
When using the constructor with a host name rather than a string representation of an IP address, the address family
restricts DNS resolution to prefer addresses of the specified address family value. When using the constructor with the
address family specified as Unknown, the address family of the DnsEndPoint will remain Unknown even after use. The
AddressFamily property of any Socket that is created by calls to the ConnectAsync method will be the address family
of the first address to which a connection can be successfully established (not necessarily the first address to be
resolved).
DnsEndPoint.Equals DnsEndPoint.Equals
I n this Article
Compares two DnsEndPoint objects.
public override bool Equals (object comparand);
override this.Equals : obj -> bool

Parameters
comparand Object Object
A DnsEndPoint instance to compare to the current instance.
Returns
Boolean Boolean
true if the two DnsEndPoint instances are equal; otherwise, false .

Remarks
The Equals method compares the current DnsEndPoint instance with the comparand parameter and returns true if
the two instances contain the same endpoint.
DnsEndPoint.GetHashCode DnsEndPoint.GetHashCode
I n this Article
Returns a hash value for a DnsEndPoint.
public override int GetHashCode ();
override this.GetHashCode : unit -> int

Returns
Int32 Int32
An integer hash value for the DnsEndPoint.

Remarks
The GetHashCode method returns a hash code of the DnsEndPoint. This value can be used as a key in hash tables.
DnsEndPoint.Host DnsEndPoint.Host
I n this Article
Gets the host name or string representation of the Internet Protocol (IP ) address of the host.
public string Host { get; }
member this.Host : string

Returns
String String
A host name or string representation of an IP address.

Remarks
The Host property indicates the host name or string representation of the IP address for an instance of the
DnsEndPoint class.
DnsEndPoint.Port DnsEndPoint.Port
I n this Article
Gets the port number of the DnsEndPoint.
public int Port { get; }
member this.Port : int

Returns
Int32 Int32
An integer value in the range 0 to 0xffff indicating the port number of the DnsEndPoint.
DnsEndPoint.ToString DnsEndPoint.ToString
I n this Article
Returns the host name or string representation of the IP address and port number of the DnsEndPoint.
public override string ToString ();
override this.ToString : unit -> string

Returns
String String
A string containing the address family, host name or IP address string, and the port number of the specified
DnsEndPoint.

Remarks
The ToString method returns a string that contains the address family, the host name or IP address string, and the port
number.
DnsPermission DnsPermission Class
Controls rights to access Domain Name System (DNS ) servers on the network.

D eclaration
[System.Serializable]
public sealed class DnsPermission : System.Security.CodeAccessPermission,
System.Security.Permissions.IUnrestrictedPermission
type DnsPermission = class
inherit CodeAccessPermission
interface IUnrestrictedPermission

I nheritance H ierarchy
Object Object
CodeAccessPermission CodeAccessPermission

Remarks
The default permissions allow all local and Intranet zone applications to access DNS services, and no DNS permission
for Internet zone applications.

Constructors
DnsPermission(PermissionState)
DnsPermission(PermissionState)

Creates a new instance of the DnsPermission class that either allows unrestricted DNS access or disallows DNS
access.

Methods
Copy()
Copy()

Creates an identical copy of the current permission instance.

FromXml(SecurityElement)
FromXml(SecurityElement)

Reconstructs a DnsPermission instance from an XML encoding.

Intersect(IPermission)
Intersect(IPermission)

Creates a permission instance that is the intersection of the current permission instance and the specified
permission instance.
IsSubsetOf(IPermission)
IsSubsetOf(IPermission)

Determines whether the current permission instance is a subset of the specified permission instance.

IsUnrestricted()
IsUnrestricted()

Checks the overall permission state of the object.

ToXml()
ToXml()

Creates an XML encoding of a DnsPermission instance and its current state.

Union(IPermission)
Union(IPermission)

Creates a permission instance that is the union of the current permission instance and the specified permission
instance.
DnsPermission.Copy DnsPermission.Copy
I n this Article
Creates an identical copy of the current permission instance.
public override System.Security.IPermission Copy ();
override this.Copy : unit -> System.Security.IPermission

Returns
IPermission IPermission
A new instance of the DnsPermission class that is an identical copy of the current instance.

Examples
The following example creates an identical copy of an existing DnsPermission instance.
public void UseDns() {
// Create a DnsPermission instance.
DnsPermission myPermission = new DnsPermission(PermissionState.Unrestricted);
// Check for permission.
myPermission.Demand();
// Create an identical copy of the above 'DnsPermission' object.
DnsPermission myPermissionCopy = (DnsPermission)myPermission.Copy();
Console.WriteLine("Attributes and Values of 'DnsPermission' instance :");
// Print the attributes and values.
PrintKeysAndValues(myPermission.ToXml().Attributes);
Console.WriteLine("Attribute and values of copied instance :");
PrintKeysAndValues(myPermissionCopy.ToXml().Attributes);
}

private void PrintKeysAndValues(Hashtable myHashtable) {


// Get the enumerator that can iterate through the hash table.
IDictionaryEnumerator myEnumerator = myHashtable.GetEnumerator();
Console.WriteLine(" -KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}

Remarks
A copy of a DnsPermission instance provides the same access to DNS servers as the original permission instance.
DnsPermission DnsPermission
I n this Article
Creates a new instance of the DnsPermission class that either allows unrestricted DNS access or disallows DNS access.
public DnsPermission (System.Security.Permissions.PermissionState state);
new System.Net.DnsPermission : System.Security.Permissions.PermissionState ->
System.Net.DnsPermission

Parameters
state PermissionState PermissionState
One of the PermissionState values.
Exceptions
ArgumentException ArgumentException
state is not a valid PermissionState value.

Examples
The following example creates an instance of the DnsPermission class.
public void useDns() {

// Create a DnsPermission instance.


DnsPermission permission = new DnsPermission(PermissionState.Unrestricted);

// Check for permission.


permission.Demand();
// Create a SecurityElement object to hold XML encoding of the DnsPermission instance.
SecurityElement securityElementObj = permission.ToXml();
Console.WriteLine("Tag, Attributes and Values of 'DnsPermission' instance :");
Console.WriteLine("
Tag :" + securityElementObj.Tag);
// Print the attributes and values.
PrintKeysAndValues(securityElementObj.Attributes);
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash table.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine("
-KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}

Remarks
If state is Unrestricted, the DnsPermission instance passes all demands. If state contains any other value, the
DnsPermission instance fails all demands.
DnsPermission.FromXml DnsPermission.FromXml
I n this Article
Reconstructs a DnsPermission instance from an XML encoding.
public override void FromXml (System.Security.SecurityElement securityElement);
override this.FromXml : System.Security.SecurityElement -> unit

Parameters
securityElement SecurityElement SecurityElement
The XML encoding to use to reconstruct the DnsPermission instance.
Exceptions
ArgumentNullException ArgumentNullException
securityElement is null .
ArgumentException ArgumentException
securityElement is not a DnsPermission element.

Examples
The following example reconstructs a DnsPermission instance from an XML encoding.
public void ConstructDnsPermission() {
try
{
// Create a DnsPermission instance.
DnsPermission permission = new DnsPermission(PermissionState.None);
// Create a SecurityElement instance by calling the ToXml method on the
// DnsPermission instance.
// Print its attributes, which hold the XML encoding of the DnsPermission
// instance.
Console.WriteLine("Attributes and Values of 'DnsPermission' instance :");
PrintKeysAndValues(permission.ToXml().Attributes);

// Create a SecurityElement instance.


SecurityElement securityElementObj = new SecurityElement("IPermission");
// Add attributes and values of the SecurityElement instance corresponding to
// the permission instance.
securityElementObj.AddAttribute("version", "1");
securityElementObj.AddAttribute("Unrestricted", "true");
securityElementObj.AddAttribute("class","System.Net.DnsPermission");

// Reconstruct a DnsPermission instance from an XML encoding.


DnsPermission permission1 = new DnsPermission(PermissionState.None);
permission1.FromXml(securityElementObj);

// Print the attributes and values of the constructed DnsPermission object.


Console.WriteLine("After reconstruction Attributes and Values of new DnsPermission instance :");
PrintKeysAndValues(permission1.ToXml().Attributes);
}
catch(NullReferenceException e)
{
Console.WriteLine("NullReferenceException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(SecurityException e)
{
Console.WriteLine("SecurityException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash table.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine(" -KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}
Remarks
The FromXml method reconstructs a DnsPermission instance from an XML encoding defined by the SecurityElement
class.
Use the ToXml method to XML -encode the DnsPermission instance, including state information.
See SecurityElementSecurityElement
Also
DnsPermission.Intersect DnsPermission.Intersect
I n this Article
Creates a permission instance that is the intersection of the current permission instance and the specified permission
instance.

public override System.Security.IPermission Intersect (System.Security.IPermission target);


override this.Intersect : System.Security.IPermission -> System.Security.IPermission

Parameters
target IPermission IPermission
The DnsPermission instance to intersect with the current instance.
Returns
IPermission IPermission
A DnsPermission instance that represents the intersection of the current DnsPermission instance with the specified
DnsPermission instance, or null if the intersection is empty. If both the current instance and target are unrestricted,
this method returns a new DnsPermission instance that is unrestricted; otherwise, it returns null .
Exceptions
ArgumentException ArgumentException
target is neither a DnsPermission nor null .

Examples
The following example creates a permission instance that is the intersection of the current permission instance and the
specified permission instance.
public void useDns() {
// Create a DnsPermission instance.
dnsPermission1 = new DnsPermission(PermissionState.Unrestricted);
dnsPermission2 = new DnsPermission(PermissionState.None);
// Check for permission.
dnsPermission1.Demand();
dnsPermission2.Demand();
Console.WriteLine("Attributes and Values of first DnsPermission instance :");
PrintKeysAndValues(dnsPermission1.ToXml().Attributes);
Console.WriteLine("Attributes and Values of second DnsPermission instance :");
PrintKeysAndValues(dnsPermission2.ToXml().Attributes);
Console.WriteLine("Union of both instances : ");
MyUnion();
Console.WriteLine("Intersection of both instances : ");
MyIntersection();
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash tabble.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine(" -KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}
// Create a DnsPermission instance that is the intersection of current
// DnsPermission instance and the specified DnsPermission instance.
private void MyIntersection()
{
DnsPermission permission = (DnsPermission)dnsPermission1.Intersect(dnsPermission2);
// Print the attributes and the values of the intersection instance of
// DnsPermission.
PrintKeysAndValues(permission.ToXml().Attributes);
}

Remarks
The Intersect method returns a DnsPermission instance that allows the access defined by both the current
DnsPermission instance and the specified DnsPermission instance. Any demand must pass both permissions to pass
their intersection.
DnsPermission.IsSubsetOf DnsPermission.IsSubsetOf
I n this Article
Determines whether the current permission instance is a subset of the specified permission instance.
public override bool IsSubsetOf (System.Security.IPermission target);
override this.IsSubsetOf : System.Security.IPermission -> bool

Parameters
target IPermission IPermission
The second DnsPermission instance to be tested for the subset relationship.
Returns
Boolean Boolean
false if the current instance is unrestricted and target is either null or unrestricted; otherwise, true .
Exceptions
ArgumentException ArgumentException
target is neither a DnsPermission nor null .

Examples
The following example uses the IsSubsetOf method to determine whether the current permission instance is a subset
of the specified permission instance.
public void useDns() {
// Create a DnsPermission instance.
permission = new DnsPermission(PermissionState.Unrestricted);
DnsPermission dnsPermission1 = new DnsPermission(PermissionState.None);
// Check for permission.
permission.Demand();
dnsPermission1.Demand();
// Print the attributes and values.
Console.WriteLine("Attributes and Values of 'DnsPermission' instance :");
PrintKeysAndValues(permission.ToXml().Attributes);
Console.WriteLine("Attributes and Values of specified 'DnsPermission' instance :");
PrintKeysAndValues(dnsPermission1.ToXml().Attributes);
Subset(dnsPermission1);
}

private void Subset(DnsPermission Permission1)


{
if(permission.IsSubsetOf(Permission1))
Console.WriteLine("Current 'DnsPermission' instance is a subset of specified 'DnsPermission'
instance.");
else
Console.WriteLine("Current 'DnsPermission' instance is not a subset of specified
'DnsPermission' instance.");
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash table.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine(" -KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}

Remarks
The current DnsPermission instance is a subset of the specified DnsPermission instance if the current DnsPermission
instance specifies a set of operations that is wholly contained by the specified DnsPermission instance.
If the IsSubsetOf method returns true , the current DnsPermission instance allows no more access to DNS servers
than does the specified DnsPermission instance.
DnsPermission.IsUnrestricted DnsPermission.Is
Unrestricted
I n this Article
Checks the overall permission state of the object.

public bool IsUnrestricted ();


override this.IsUnrestricted : unit -> bool

Returns
Boolean Boolean
true if the DnsPermission instance was created with Unrestricted; otherwise, false .

Examples
The following example uses the IsUnrestricted method to check the overall permission state of the object.
public void useDns() {
// Create a DnsPermission instance.
DnsPermission permission = new DnsPermission(PermissionState.Unrestricted);
// Check for permission.
permission.Demand();
Console.WriteLine("Attributes and Values of DnsPermission instance :");
// Print the attributes and values.
PrintKeysAndValues(permission.ToXml().Attributes);
// Check the permission state.
if (permission.IsUnrestricted())
Console.WriteLine("Overall permissions : Unrestricted");
else
Console.WriteLine("Overall permissions : Restricted");
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash table.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine(" -KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}
DnsPermission.ToXml DnsPermission.ToXml
I n this Article
Creates an XML encoding of a DnsPermission instance and its current state.
public override System.Security.SecurityElement ToXml ();
override this.ToXml : unit -> System.Security.SecurityElement

Returns
SecurityElement SecurityElement
A SecurityElement instance that contains an XML -encoded representation of the security object, including state
information.

Examples
The following example creates an XML encoding of a DnsPermission instance.
public void useDns() {

// Create a DnsPermission instance.


DnsPermission permission = new DnsPermission(PermissionState.Unrestricted);

// Check for permission.


permission.Demand();
// Create a SecurityElement object to hold XML encoding of the DnsPermission instance.
SecurityElement securityElementObj = permission.ToXml();
Console.WriteLine("Tag, Attributes and Values of 'DnsPermission' instance :");
Console.WriteLine("
Tag :" + securityElementObj.Tag);
// Print the attributes and values.
PrintKeysAndValues(securityElementObj.Attributes);
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash table.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine("
-KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}

Remarks
The ToXml method creates a SecurityElement instance to XML -encode a representation of the DnsPermission instance,
including state information.
Use the FromXml method to restore the state information from a SecurityElement instance.
DnsPermission.Union DnsPermission.Union
I n this Article
Creates a permission instance that is the union of the current permission instance and the specified permission
instance.

public override System.Security.IPermission Union (System.Security.IPermission target);


override this.Union : System.Security.IPermission -> System.Security.IPermission

Parameters
target IPermission IPermission
The DnsPermission instance to combine with the current instance.
Returns
IPermission IPermission
A DnsPermission instance that represents the union of the current DnsPermission instance with the specified
DnsPermission instance. If target is null , this method returns a copy of the current instance. If the current instance
or target is unrestricted, this method returns a DnsPermission instance that is unrestricted; otherwise, it returns a
DnsPermission instance that is restricted.
Exceptions
ArgumentException ArgumentException
target is neither a DnsPermission nor null .

Examples
The following example creates a permission instance that is the union of the current permission instance and the
specified permission instance.
private void MyUnion()
{
// Create a DnsPermission instance that is the union of the current DnsPermission
// instance and the specified DnsPermission instance.
DnsPermission permission = (DnsPermission)dnsPermission1.Union(dnsPermission2);
// Print the attributes and the values of the union instance of DnsPermission.
PrintKeysAndValues(permission.ToXml().Attributes);
}
public void useDns() {
// Create a DnsPermission instance.
dnsPermission1 = new DnsPermission(PermissionState.Unrestricted);
dnsPermission2 = new DnsPermission(PermissionState.None);
// Check for permission.
dnsPermission1.Demand();
dnsPermission2.Demand();
Console.WriteLine("Attributes and Values of first DnsPermission instance :");
PrintKeysAndValues(dnsPermission1.ToXml().Attributes);
Console.WriteLine("Attributes and Values of second DnsPermission instance :");
PrintKeysAndValues(dnsPermission2.ToXml().Attributes);
Console.WriteLine("Union of both instances : ");
MyUnion();
Console.WriteLine("Intersection of both instances : ");
MyIntersection();
}

private void PrintKeysAndValues(Hashtable myList) {


// Get the enumerator that can iterate through the hash tabble.
IDictionaryEnumerator myEnumerator = myList.GetEnumerator();
Console.WriteLine(" -KEY- -VALUE-");
while (myEnumerator.MoveNext())
Console.WriteLine(" {0}: {1}", myEnumerator.Key, myEnumerator.Value);
Console.WriteLine();
}

Remarks
The Union method returns a DnsPermission instance that allows the access defined by either the current
DnsPermission instance or the specified DnsPermission instance. Any demand that passes either permission passes
their union.
DnsPermissionAttribute DnsPermissionAttribute Class
Specifies permission to request information from Domain Name Servers.

D eclaration
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Constructor | System.AttributeTargets.Method |
System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Struct | System.AttributeTargets.Constructor |
System.AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
[System.Serializable]
public sealed class DnsPermissionAttribute :
System.Security.Permissions.CodeAccessSecurityAttribute
type DnsPermissionAttribute = class
inherit CodeAccessSecurityAttribute

I nheritance H ierarchy
Object Object
Attribute Attribute
SecurityAttribute SecurityAttribute
CodeAccessSecurityAttribute CodeAccessSecurityAttribute

Remarks
The security information declared by DnsPermissionAttribute is stored in the metadata of the attribute target, which is
the class to which the DnsPermissionAttribute is applied. The system then accesses this information at run time. The
SecurityAction that is passed to the constructor determines the allowable DNS targets.
These security attributes are used only for Declarative Security. For Imperative Security, use the corresponding
DnsPermission class.
Security access is either fully restricted or fully unrestricted. Set the Unrestricted property to true to grant access, or
false for no access. Set this property as a named parameter.

For more information about using attributes, see Attributes.

Constructors
DnsPermissionAttribute(SecurityAction)
DnsPermissionAttribute(SecurityAction)

Initializes a new instance of the DnsPermissionAttribute class with the specified SecurityAction value.

Methods
CreatePermission()
CreatePermission()

Creates and returns a new instance of the DnsPermission class.


See Also
CodeAccessSecurityAttribute CodeAccessSecurityAttribute
DnsPermissionAttribute.CreatePermission DnsPermission
Attribute.CreatePermission
I n this Article
Creates and returns a new instance of the DnsPermission class.

public override System.Security.IPermission CreatePermission ();


override this.CreatePermission : unit -> System.Security.IPermission

Returns
IPermission IPermission
A DnsPermission that corresponds to the security declaration.

Remarks
The CreatePermission method is called by the security system, not by application code.
The security information described by DnsPermissionAttribute is stored in the metadata of the attribute target, which is
the class to which DnsPermissionAttribute is applied. The system then accesses the information at run time and calls
CreatePermission. The system uses the returned IPermission to enforce the specified security requirements.
DnsPermissionAttribute DnsPermissionAttribute
I n this Article
Initializes a new instance of the DnsPermissionAttribute class with the specified SecurityAction value.
public DnsPermissionAttribute (System.Security.Permissions.SecurityAction action);
new System.Net.DnsPermissionAttribute : System.Security.Permissions.SecurityAction ->
System.Net.DnsPermissionAttribute

Parameters
action SecurityAction SecurityAction
One of the SecurityAction values.
Exceptions
ArgumentException ArgumentException
The action parameter is not a valid SecurityAction.

Examples
The following example uses DnsPermissionAttribute to apply declarative security to a custom class.
//Uses the DnsPermissionAttribute to restrict access only to those who have permission.
[DnsPermission(SecurityAction.Demand, Unrestricted = true)]
public class MyClass
{
public static IPAddress GetIPAddress()
{
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
return ipAddress;
}
public static void Main()
{
try
{
//Grants Access.
Console.WriteLine(" Access granted
The local host IP Address is :" +
MyClass.GetIPAddress().ToString());
}
// Denies Access.
catch (SecurityException securityException)
{
Console.WriteLine("Access denied");
Console.WriteLine(securityException.ToString());
}

Remarks
The SecurityAction value that is passed to this constructor specifies the allowable DnsPermissionAttribute targets.
See SecurityActionSecurityAction
Also
DownloadDataCompletedEventArgs DownloadData
CompletedEventArgs Class
Provides data for the DownloadDataCompleted event.

D eclaration
public class DownloadDataCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type DownloadDataCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to the DownloadDataCompletedEventHandler.

Properties
Result
Result

Gets the data that is downloaded by a DownloadDataAsync method.


DownloadDataCompletedEventArgs.Result Download
DataCompletedEventArgs.Result
I n this Article
Gets the data that is downloaded by a DownloadDataAsync method.

public byte[] Result { get; }


member this.Result : byte[]

Returns
Byte[]
A Byte array that contains the downloaded data.

Examples
The following code example displays the value of this property.
private static void DownloadDataCallback (Object sender, DownloadDataCompletedEventArgs e)
{
System.Threading.AutoResetEvent waiter = (System.Threading.AutoResetEvent)e.UserState;

try
{
// If the request was not canceled and did not throw
// an exception, display the resource.
if (!e.Cancelled && e.Error == null)
{
byte[] data = (byte[])e.Result;
string textData = System.Text.Encoding.UTF8.GetString (data);

Console.WriteLine (textData);
}
}
finally
{
// Let the main application thread resume.
waiter.Set ();
}
}

Remarks
You should check the Error and Cancelled properties before using the data that is returned by this property. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
DownloadDataCompletedEventHandler DownloadData
CompletedEventHandler Delegate
Represents the method that will handle the DownloadDataCompleted event of a WebClient.

D eclaration
public delegate void DownloadDataCompletedEventHandler(object sender,
DownloadDataCompletedEventArgs e);
type DownloadDataCompletedEventHandler = delegate of obj * DownloadDataCompletedEventArgs ->
unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a DownloadDataCompletedEventHandler delegate, you identify the method that will handle the
event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is
called whenever the event occurs, unless you remove the delegate. For more information about event handler
delegates, see Handling and Raising Events.
DownloadProgressChangedEventArgs DownloadProgress
ChangedEventArgs Class
Provides data for the DownloadProgressChanged event of a WebClient.

D eclaration
public class DownloadProgressChangedEventArgs : System.ComponentModel.ProgressChangedEventArgs
type DownloadProgressChangedEventArgs = class
inherit ProgressChangedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
ProgressChangedEventArgs ProgressChangedEventArgs

Remarks
Instances of this class are passed to the DownloadProgressChangedEventHandler.

Properties
BytesReceived
BytesReceived

Gets the number of bytes received.

TotalBytesToReceive
TotalBytesToReceive

Gets the total number of bytes in a WebClient data download operation.


DownloadProgressChangedEventArgs.BytesReceived
DownloadProgressChangedEventArgs.BytesReceived
I n this Article
Gets the number of bytes received.

public long BytesReceived { get; }


member this.BytesReceived : int64

Returns
Int64 Int64
An Int64 value that indicates the number of bytes received.

Examples
The following code example shows an implementation of a handler for the DownloadProgressChanged event. The
method displays the value of this property.
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} uploaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesSent,
e.TotalBytesToSend,
e.ProgressPercentage);
}
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}

Remarks
To determine what percentage of the transfer has occurred, use the ProgressPercentage property.
DownloadProgressChangedEventArgs.TotalBytesTo
Receive DownloadProgressChangedEventArgs.TotalBytes
ToReceive
I n this Article
Gets the total number of bytes in a WebClient data download operation.
public long TotalBytesToReceive { get; }
member this.TotalBytesToReceive : int64

Returns
Int64 Int64
An Int64 value that indicates the number of bytes that will be received.

Examples
The following code example shows an implementation of a handler for the DownloadProgressChanged event. The
method displays the value of this property.
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} uploaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesSent,
e.TotalBytesToSend,
e.ProgressPercentage);
}
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}

Remarks
To determine the number of bytes already received, use the BytesReceived property.
To determine what percentage of the transfer has occurred, use the ProgressPercentage property.
DownloadProgressChangedEventHandler Download
ProgressChangedEventHandler Delegate
Represents the method that will handle the DownloadProgressChanged event of a WebClient.

D eclaration
public delegate void DownloadProgressChangedEventHandler(object sender,
DownloadProgressChangedEventArgs e);
type DownloadProgressChangedEventHandler = delegate of obj * DownloadProgressChangedEventArgs ->
unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a DownloadProgressChangedEventHandler delegate, you identify the method that will handle the
event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is
called whenever the event occurs, unless you remove the delegate. For more information about event handler
delegates, see Handling and Raising Events. Handling and Raising Events
Note

If the server does not send the size of the downloaded file (such as in the case of a passive FTP connection),
ProgressPercentage may always be zero.
DownloadStringCompletedEventArgs DownloadString
CompletedEventArgs Class
Provides data for the DownloadStringCompleted event.

D eclaration
public class DownloadStringCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type DownloadStringCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to the DownloadStringCompletedEventHandler.

Properties
Result
Result

Gets the data that is downloaded by a DownloadStringAsync method.


DownloadStringCompletedEventArgs.Result Download
StringCompletedEventArgs.Result
I n this Article
Gets the data that is downloaded by a DownloadStringAsync method.

public string Result { get; }


member this.Result : string

Returns
String String
A String that contains the downloaded data.

Examples
The following code example displays the value of this property.
private static void DownloadStringCallback2 (Object sender, DownloadStringCompletedEventArgs e)
{
// If the request was not canceled and did not throw
// an exception, display the resource.
if (!e.Cancelled && e.Error == null)
{
string textString = (string)e.Result;

Console.WriteLine (textString);
}
}

Remarks
You should check the Error and Cancelled properties before using the data that is returned by this property. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
DownloadStringCompletedEventHandler Download
StringCompletedEventHandler Delegate
Represents the method that will handle the DownloadStringCompleted event of a WebClient.

D eclaration
public delegate void DownloadStringCompletedEventHandler(object sender,
DownloadStringCompletedEventArgs e);
type DownloadStringCompletedEventHandler = delegate of obj * DownloadStringCompletedEventArgs ->
unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a DownloadStringCompletedEventHandler delegate, you identify the method that will handle the
event. To associate the event with your event handler, add an instance of the delegate to the event. The event handler is
called whenever the event occurs, unless you remove the delegate. For more information about event handler
delegates, see Handling and Raising Events.
EndPoint EndPoint Class
Identifies a network address. This is an abstract class.

D eclaration
[System.Serializable]
public abstract class EndPoint
type EndPoint = class

I nheritance H ierarchy
Object Object

Remarks
The EndPoint class provides an abstract base class that represents a network resource or service. Descendant classes
combine network connection information to form a connection point to a service.

Constructors
EndPoint()
EndPoint()

Initializes a new instance of the EndPoint class.

Properties
AddressFamily
AddressFamily

Gets the address family to which the endpoint belongs.

Methods
Create(SocketAddress)
Create(SocketAddress)

Creates an EndPoint instance from a SocketAddress instance.

Serialize()
Serialize()

Serializes endpoint information into a SocketAddress instance.

See Also
IPEndPoint IPEndPoint
EndPoint.AddressFamily EndPoint.AddressFamily
I n this Article
Gets the address family to which the endpoint belongs.
public virtual System.Net.Sockets.AddressFamily AddressFamily { get; }
member this.AddressFamily : System.Net.Sockets.AddressFamily

Returns
AddressFamily AddressFamily
One of the AddressFamily values.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property when the property is not overridden in a descendant class.

Remarks
The AddressFamily property specifies the addressing scheme that is used by the endpoint's underlying network
protocol.
EndPoint.Create EndPoint.Create
I n this Article
Creates an EndPoint instance from a SocketAddress instance.
public virtual System.Net.EndPoint Create (System.Net.SocketAddress socketAddress);
abstract member Create : System.Net.SocketAddress -> System.Net.EndPoint
override this.Create : System.Net.SocketAddress -> System.Net.EndPoint

Parameters
socketAddress SocketAddress SocketAddress
The socket address that serves as the endpoint for a connection.
Returns
EndPoint EndPoint
A new EndPoint instance that is initialized from the specified SocketAddress instance.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method when the method is not overridden in a descendant class.
EndPoint
I n this Article
Initializes a new instance of the EndPoint class.
protected EndPoint ();
EndPoint.Serialize EndPoint.Serialize
I n this Article
Serializes endpoint information into a SocketAddress instance.
public virtual System.Net.SocketAddress Serialize ();
abstract member Serialize : unit -> System.Net.SocketAddress
override this.Serialize : unit -> System.Net.SocketAddress

Returns
SocketAddress SocketAddress
A SocketAddress instance that contains the endpoint information.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method when the method is not overridden in a descendant class.
EndpointPermission EndpointPermission Class
Defines an endpoint that is authorized by a SocketPermission instance.

D eclaration
[System.Serializable]
public class EndpointPermission
type EndpointPermission = class

I nheritance H ierarchy
Object Object

Remarks
The EndpointPermission class defines a network endpoint, including host name, network port number, and transport
type used to make the connection.
Note

Avoid creating EndPoint permissions using host names because these names will have to be resolved to IP address,
which could block the stack.

Properties
Hostname
Hostname

Gets the DNS host name or IP address of the server that is associated with this endpoint.

Port
Port

Gets the network port number that is associated with this endpoint.

Transport
Transport

Gets the transport type that is associated with this endpoint.

Methods
Equals(Object)
Equals(Object)

Determines whether the specified Object is equal to the current Object .

GetHashCode()
GetHashCode()
Serves as a hash function for a particular type.

ToString()
ToString()

Returns a string that represents the current EndpointPermission instance.


EndpointPermission.Equals EndpointPermission.Equals
I n this Article
Determines whether the specified Object is equal to the current Object .

public override bool Equals (object obj);


override this.Equals : obj -> bool

Parameters
obj Object Object
The Object to compare with the current Object .
Returns
Boolean Boolean
true if the specified Object is equal to the current Object ; otherwise, false .
EndpointPermission.GetHashCode EndpointPermission.
GetHashCode
I n this Article
Serves as a hash function for a particular type.

public override int GetHashCode ();


override this.GetHashCode : unit -> int

Returns
Int32 Int32
A hash code for the current Object.
EndpointPermission.Hostname EndpointPermission.
Hostname
I n this Article
Gets the DNS host name or IP address of the server that is associated with this endpoint.

public string Hostname { get; }


member this.Hostname : string

Returns
String String
A string that contains the DNS host name or IP address of the server.
EndpointPermission.Port EndpointPermission.Port
I n this Article
Gets the network port number that is associated with this endpoint.
public int Port { get; }
member this.Port : int

Returns
Int32 Int32
The network port number that is associated with this request, or AllPorts.
EndpointPermission.ToString EndpointPermission.To
String
I n this Article
Returns a string that represents the current EndpointPermission instance.

public override string ToString ();


override this.ToString : unit -> string

Returns
String String
A string that represents the current EndpointPermission instance.

Remarks
The ToString method returns a string that represents the contents for the EndpointPermission instance. The string is in
the form Hostname # Port # Transport.
EndpointPermission.Transport EndpointPermission.
Transport
I n this Article
Gets the transport type that is associated with this endpoint.

public System.Net.TransportType Transport { get; }


member this.Transport : System.Net.TransportType

Returns
TransportType TransportType
One of the TransportType values.
FileWebRequest FileWebRequest Class
Provides a file system implementation of the WebRequest class.

D eclaration
[System.Serializable]
public class FileWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable
type FileWebRequest = class
inherit WebRequest
interface ISerializable

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
WebRequest WebRequest

Remarks
The FileWebRequest class implements the WebRequest abstract base class for Uniform Resource Identifiers (URIs)
that use the file:// scheme to request local files.
Do not use the FileWebRequest constructor. Use the WebRequest.Create method to initialize new instances of the
FileWebRequest class. If the URI scheme is file:// , the Create method returns a FileWebRequest object.
The GetResponse method makes a synchronous request for the file specified in the RequestUri property and returns a
FileWebResponse object that contains the response. You can make an asynchronous request for the file using the
BeginGetResponse and EndGetResponse methods.
When you want to write data to a file, the GetRequestStream method returns a Stream instance to write to. The
BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the write data stream.
The FileWebRequest class relies on the File class for error handling and code access security.

Constructors
FileWebRequest(SerializationInfo, StreamingContext)
FileWebRequest(SerializationInfo, StreamingContext)

Initializes a new instance of the FileWebRequest class from the specified instances of the SerializationInfo and
StreamingContext classes.

Properties
ConnectionGroupName
ConnectionGroupName

Gets or sets the name of the connection group for the request. This property is reserved for future use.

ContentLength
ContentLength
Gets or sets the content length of the data being sent.

ContentType
ContentType

Gets or sets the content type of the data being sent. This property is reserved for future use.

Credentials
Credentials

Gets or sets the credentials that are associated with this request. This property is reserved for future use.

Headers
Headers

Gets a collection of the name/value pairs that are associated with the request. This property is reserved for future
use.

Method
Method

Gets or sets the protocol method used for the request. This property is reserved for future use.

PreAuthenticate
PreAuthenticate

Gets or sets a value that indicates whether to preauthenticate a request. This property is reserved for future use.

Proxy
Proxy

Gets or sets the network proxy to use for this request. This property is reserved for future use.

RequestUri
RequestUri

Gets the Uniform Resource Identifier (URI) of the request.

Timeout
Timeout

Gets or sets the length of time until the request times out.
UseDefaultCredentials
UseDefaultCredentials

Always throws a NotSupportedException.

Methods
Abort()
Abort()

Cancels a request to an Internet resource.

BeginGetRequestStream(AsyncCallback, Object)
BeginGetRequestStream(AsyncCallback, Object)

Begins an asynchronous request for a Stream object to use to write data.

BeginGetResponse(AsyncCallback, Object)
BeginGetResponse(AsyncCallback, Object)

Begins an asynchronous request for a file system resource.

EndGetRequestStream(IAsyncResult)
EndGetRequestStream(IAsyncResult)

Ends an asynchronous request for a Stream instance that the application uses to write data.

EndGetResponse(IAsyncResult)
EndGetResponse(IAsyncResult)

Ends an asynchronous request for a file system resource.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

GetRequestStream()
GetRequestStream()

Returns a Stream object for writing data to the file system resource.

GetRequestStreamAsync()
GetRequestStreamAsync()
GetResponse()
GetResponse()

Returns a response to a file system request.

GetResponseAsync()
GetResponseAsync()

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo object with the required data to serialize the FileWebRequest.
FileWebRequest.Abort FileWebRequest.Abort
I n this Article
Cancels a request to an Internet resource.
public override void Abort ();
override this.Abort : unit -> unit

Remarks
The Abort method cancels a request to a resource. After a request is canceled, calling the GetResponse,
BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream method
causes a WebException with the Status property set to RequestCanceled.
Note This member outputs trace information when you enable network tracing in your application. For more
information, see Network Tracing in the .NET Framework.
FileWebRequest.BeginGetRequestStream FileWeb
Request.BeginGetRequestStream
I n this Article
Begins an asynchronous request for a Stream object to use to write data.

public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state);


override this.BeginGetRequestStream : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
The AsyncCallback delegate.
state Object Object
An object that contains state information for this request.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that references the asynchronous request.
Exceptions
ProtocolViolationException ProtocolViolationException
The Method property is GET and the application writes to the stream.
InvalidOperationException InvalidOperationException
The stream is being used by a previous call to BeginGetRequestStream(AsyncCallback, Object).
ApplicationException ApplicationException
No write stream is available.
WebException WebException
The FileWebRequest was aborted.

Examples
The following code example uses BeginGetRequestStream to make an asynchronous request for a Stream object.

public class RequestDeclare


{
public FileWebRequest myFileWebRequest;
public String userinput;

public RequestDeclare()
{
myFileWebRequest = null;
}
}

class FileWebRequest_reqbeginend
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public static ManualResetEvent allDone = new ManualResetEvent(false);

static void Main(string[] args)


{
if (args.Length < 1)
{
Console.WriteLine("
Please enter the file name as command line parameter:");
Console.WriteLine("Usage:FileWebRequest_reqbeginend
<systemname>/<sharedfoldername>/<filename>
Example:FileWebRequest_reqbeginend shafeeque/shaf/hello.txt");

}
else
{

try
{

// Place a webrequest.
WebRequest myWebRequest= WebRequest.Create("file://"+args[0]);

// Create an instance of the 'RequestDeclare' and associate the 'myWebRequest' to it.


RequestDeclare requestDeclare = new RequestDeclare();
requestDeclare.myFileWebRequest = (FileWebRequest)myWebRequest;
// Set the 'Method' property of 'FileWebRequest' object to 'POST' method.
requestDeclare.myFileWebRequest.Method="POST";
Console.WriteLine("Enter the string you want to write into the file:");
requestDeclare.userinput = Console.ReadLine();

// Begin the Asynchronous request for getting file content using 'BeginGetRequestStream()'
method .
IAsyncResult r=(IAsyncResult) requestDeclare.myFileWebRequest.BeginGetRequestStream(new
AsyncCallback(ReadCallback),requestDeclare);
allDone.WaitOne();

Console.Read();
}
catch(ProtocolViolationException e)
{
Console.WriteLine("ProtocolViolationException is :"+e.Message);
}
catch(InvalidOperationException e)
{
Console.WriteLine("InvalidOperationException is :"+e.Message);
}
catch(UriFormatException e)
{
Console.WriteLine("UriFormatExceptionException is :"+e.Message);
}
}
}

private static void ReadCallback(IAsyncResult ar)


{

try
{

// State of the request is asynchronous.


RequestDeclare requestDeclare=(RequestDeclare) ar.AsyncState;
FileWebRequest myFileWebRequest=requestDeclare.myFileWebRequest;
String sendToFile = requestDeclare.userinput;

// End the Asynchronus request by calling the 'EndGetRequestStream()' method.


Stream readStream=myFileWebRequest.EndGetRequestStream(ar);
Stream readStream=myFileWebRequest.EndGetRequestStream(ar);

// Convert the string into byte array.

ASCIIEncoding encoder = new ASCIIEncoding();


byte[] byteArray = encoder.GetBytes(sendToFile);

// Write to the stream.


readStream.Write(byteArray,0,sendToFile.Length);
readStream.Close();
allDone.Set();

Console.WriteLine("
The String you entered was successfully written into the file.");
Console.WriteLine("
Press Enter to continue.");

}
catch(ApplicationException e)
{
Console.WriteLine("ApplicationException is :"+e.Message);
}

Remarks
The BeginGetRequestStream method starts an asynchronous request for a stream used to send data to a file system
resource. The callback method that implements the AsyncCallback delegate uses the EndGetRequestStream method to
return the request stream.
See GetRequestStream()GetRequestStream()
Also EndGetRequestStream(IAsyncResult)EndGetRequestStream(IAsyncResult)
Making Asynchronous Requests
FileWebRequest.BeginGetResponse FileWebRequest.
BeginGetResponse
I n this Article
Begins an asynchronous request for a file system resource.

public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state);


override this.BeginGetResponse : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
The AsyncCallback delegate.
state Object Object
An object that contains state information for this request.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that references the asynchronous request.
Exceptions
InvalidOperationException InvalidOperationException
The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object).
WebException WebException
The FileWebRequest was aborted.

Examples
The following code example uses the BeginGetResponse method to asynchronously access a file system resource.

public class RequestDeclare


{
public FileWebRequest myFileWebRequest;

public RequestDeclare()
{
myFileWebRequest = null;
}
}

class FileWebRequest_resbeginend
{

public static ManualResetEvent allDone = new ManualResetEvent(false);

static void Main(string[] args)


{

if (args.Length < 1)
{
Console.WriteLine("
Console.WriteLine("
Please enter the file name as command line parameter:");
Console.WriteLine("Usage:FileWebRequest_resbeginend
<systemname>/<sharedfoldername>/<filename>
Example:FileWebRequest_resbeginend shafeeque/shaf/hello.txt");
}
else
{
try
{

// Place a 'Webrequest'.
WebRequest myWebRequest= WebRequest.Create("file://"+args[0]);
// Create an instance of the 'RequestDeclare' and associating the 'myWebRequest' to it.
RequestDeclare myRequestDeclare = new RequestDeclare();
myRequestDeclare.myFileWebRequest = (FileWebRequest)myWebRequest;

// Begin the Asynchronous request for getting file content using 'BeginGetResponse()'
method.
IAsyncResult asyncResult =(IAsyncResult)
myRequestDeclare.myFileWebRequest.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestDeclare);
allDone.WaitOne();

}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException is :"+e.Message);
}
catch(UriFormatException e)
{
Console.WriteLine("UriFormatException is :"+e.Message);
}
}
}

private static void RespCallback(IAsyncResult ar)


{

// State of request is asynchronous.


RequestDeclare requestDeclare=(RequestDeclare) ar.AsyncState;

FileWebRequest myFileWebRequest=requestDeclare.myFileWebRequest;

// End the Asynchronus request by calling the 'EndGetResponse()' method.

FileWebResponse myFileWebResponse = (FileWebResponse) myFileWebRequest.EndGetResponse(ar);

// Reade the response into Stream.


StreamReader streamReader= new StreamReader(myFileWebResponse.GetResponseStream());

Char[] readBuffer = new Char[256];

int count = streamReader.Read( readBuffer, 0, 256 );

Console.WriteLine("The contents of the file are :


");

while (count > 0)


{
{
String str = new String(readBuffer, 0, count);
Console.WriteLine(str);
count = streamReader.Read(readBuffer, 0, 256);
}

streamReader.Close();
// Release the response object resources.
myFileWebResponse.Close();
allDone.Set();
Console.WriteLine("File reading is over.");
}

Remarks
The asynchronous callback method that implements the AsyncCallback delegate uses the EndGetResponse method to
return the actual FileWebResponse.
See GetResponse()GetResponse()
Also EndGetResponse(IAsyncResult)EndGetResponse(IAsyncResult)
Making Asynchronous Requests
FileWebRequest.ConnectionGroupName FileWeb
Request.ConnectionGroupName
I n this Article
Gets or sets the name of the connection group for the request. This property is reserved for future use.

public override string ConnectionGroupName { get; set; }


member this.ConnectionGroupName : string with get, set

Returns
String String
The name of the connection group for the request.

Remarks
The ConnectionGroupName property is currently not used by the FileWebRequest class.
FileWebRequest.ContentLength FileWebRequest.Content
Length
I n this Article
Gets or sets the content length of the data being sent.

public override long ContentLength { get; set; }


member this.ContentLength : int64 with get, set

Returns
Int64 Int64
The number of bytes of request data being sent.
Exceptions
ArgumentException ArgumentException
ContentLength is less than 0.

Examples
The following code example sets the content length of the data being sent. Refer to the complete example in the
FileWebRequest class.
// Set the ContentLength property.
myFileWebRequest.ContentLength = byteArray.Length;

string contentLength = myFileWebRequest.ContentLength.ToString ();

Console.WriteLine ("
The content length is {0}.", contentLength);
FileWebRequest.ContentType FileWebRequest.Content
Type
I n this Article
Gets or sets the content type of the data being sent. This property is reserved for future use.

public override string ContentType { get; set; }


member this.ContentType : string with get, set

Returns
String String
The content type of the data being sent.

Remarks
The ContentType property contains the media type of the data being sent. This is typically the MIME encoding of the
content. The ContentType property is currently not used by the FileWebRequest class.
FileWebRequest.Credentials FileWebRequest.Credentials
I n this Article
Gets or sets the credentials that are associated with this request. This property is reserved for future use.
public override System.Net.ICredentials Credentials { get; set; }
member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials that contains the authentication credentials that are associated with this request. The default is null .

Remarks
Because the FileWebRequest class does not authenticate requests for files from the local file system, it ignores the
contents, if any, of the Credentials property. Authentication for FileWebRequest is handled by the access control lists
for the file resource in the underlying file system.
FileWebRequest.EndGetRequestStream FileWebRequest.
EndGetRequestStream
I n this Article
Ends an asynchronous request for a Stream instance that the application uses to write data.

public override System.IO.Stream EndGetRequestStream (IAsyncResult asyncResult);


override this.EndGetRequestStream : IAsyncResult -> System.IO.Stream

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult that references the pending request for a stream.
Returns
Stream Stream
A Stream object that the application uses to write data.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .

Examples
The following example uses the EndGetRequestStream method to end the asynchronous request for a Stream object.

public class RequestDeclare


{
public FileWebRequest myFileWebRequest;
public String userinput;

public RequestDeclare()
{
myFileWebRequest = null;
}
}

class FileWebRequest_reqbeginend
{
public static ManualResetEvent allDone = new ManualResetEvent(false);

static void Main(string[] args)


{
if (args.Length < 1)
{
Console.WriteLine("
Please enter the file name as command line parameter:");
Console.WriteLine("Usage:FileWebRequest_reqbeginend
<systemname>/<sharedfoldername>/<filename>
Example:FileWebRequest_reqbeginend shafeeque/shaf/hello.txt");

}
else
{

try
try
{

// Place a webrequest.
WebRequest myWebRequest= WebRequest.Create("file://"+args[0]);

// Create an instance of the 'RequestDeclare' and associate the 'myWebRequest' to it.


RequestDeclare requestDeclare = new RequestDeclare();
requestDeclare.myFileWebRequest = (FileWebRequest)myWebRequest;
// Set the 'Method' property of 'FileWebRequest' object to 'POST' method.
requestDeclare.myFileWebRequest.Method="POST";
Console.WriteLine("Enter the string you want to write into the file:");
requestDeclare.userinput = Console.ReadLine();

// Begin the Asynchronous request for getting file content using 'BeginGetRequestStream()'
method .
IAsyncResult r=(IAsyncResult) requestDeclare.myFileWebRequest.BeginGetRequestStream(new
AsyncCallback(ReadCallback),requestDeclare);
allDone.WaitOne();

Console.Read();
}
catch(ProtocolViolationException e)
{
Console.WriteLine("ProtocolViolationException is :"+e.Message);
}
catch(InvalidOperationException e)
{
Console.WriteLine("InvalidOperationException is :"+e.Message);
}
catch(UriFormatException e)
{
Console.WriteLine("UriFormatExceptionException is :"+e.Message);
}
}
}

private static void ReadCallback(IAsyncResult ar)


{

try
{

// State of the request is asynchronous.


RequestDeclare requestDeclare=(RequestDeclare) ar.AsyncState;
FileWebRequest myFileWebRequest=requestDeclare.myFileWebRequest;
String sendToFile = requestDeclare.userinput;

// End the Asynchronus request by calling the 'EndGetRequestStream()' method.


Stream readStream=myFileWebRequest.EndGetRequestStream(ar);

// Convert the string into byte array.

ASCIIEncoding encoder = new ASCIIEncoding();


byte[] byteArray = encoder.GetBytes(sendToFile);

// Write to the stream.


readStream.Write(byteArray,0,sendToFile.Length);
readStream.Close();
allDone.Set();

Console.WriteLine("
The String you entered was successfully written into the file.");
Console.WriteLine("
Press Enter to continue.");
}
catch(ApplicationException e)
{
Console.WriteLine("ApplicationException is :"+e.Message);
}

Remarks
The EndGetRequestStream method completes an asynchronous stream request that was started by the
BeginGetRequestStream method.
Note

To avoid timing issues with garbage collection, be sure to close the response stream by calling the Close method on the
stream returned by the GetResponseStream method after calling the EndGetResponse method.
See GetRequestStream()GetRequestStream()
Also BeginGetRequestStream(AsyncCallback, Object)BeginGetRequestStream(AsyncCallback, Object)
Making Asynchronous Requests
FileWebRequest.EndGetResponse FileWebRequest.End
GetResponse
I n this Article
Ends an asynchronous request for a file system resource.

public override System.Net.WebResponse EndGetResponse (IAsyncResult asyncResult);


override this.EndGetResponse : IAsyncResult -> System.Net.WebResponse

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult that references the pending request for a response.
Returns
WebResponse WebResponse
A WebResponse that contains the response from the file system resource.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .

Examples
The following code example uses the EndGetResponse method to end an asynchronous request for a file system
resource.

public class RequestDeclare


{
public FileWebRequest myFileWebRequest;

public RequestDeclare()
{
myFileWebRequest = null;
}
}

class FileWebRequest_resbeginend
{

public static ManualResetEvent allDone = new ManualResetEvent(false);

static void Main(string[] args)


{

if (args.Length < 1)
{
Console.WriteLine("
Please enter the file name as command line parameter:");
Console.WriteLine("Usage:FileWebRequest_resbeginend
<systemname>/<sharedfoldername>/<filename>
Example:FileWebRequest_resbeginend shafeeque/shaf/hello.txt");
}
else
{
{
try
{

// Place a 'Webrequest'.
WebRequest myWebRequest= WebRequest.Create("file://"+args[0]);
// Create an instance of the 'RequestDeclare' and associating the 'myWebRequest' to it.
RequestDeclare myRequestDeclare = new RequestDeclare();
myRequestDeclare.myFileWebRequest = (FileWebRequest)myWebRequest;

// Begin the Asynchronous request for getting file content using 'BeginGetResponse()'
method.
IAsyncResult asyncResult =(IAsyncResult)
myRequestDeclare.myFileWebRequest.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestDeclare);
allDone.WaitOne();

}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException is :"+e.Message);
}
catch(UriFormatException e)
{
Console.WriteLine("UriFormatException is :"+e.Message);
}
}
}

private static void RespCallback(IAsyncResult ar)


{

// State of request is asynchronous.


RequestDeclare requestDeclare=(RequestDeclare) ar.AsyncState;

FileWebRequest myFileWebRequest=requestDeclare.myFileWebRequest;

// End the Asynchronus request by calling the 'EndGetResponse()' method.

FileWebResponse myFileWebResponse = (FileWebResponse) myFileWebRequest.EndGetResponse(ar);

// Reade the response into Stream.


StreamReader streamReader= new StreamReader(myFileWebResponse.GetResponseStream());

Char[] readBuffer = new Char[256];

int count = streamReader.Read( readBuffer, 0, 256 );

Console.WriteLine("The contents of the file are :


");

while (count > 0)


{
String str = new String(readBuffer, 0, count);
Console.WriteLine(str);
count = streamReader.Read(readBuffer, 0, 256);
}

streamReader.Close();
// Release the response object resources.
// Release the response object resources.
myFileWebResponse.Close();
allDone.Set();
Console.WriteLine("File reading is over.");
}

Remarks
The EndGetResponse method completes an asynchronous request for a file system resource that was started with the
BeginGetResponse method.
See GetResponse()GetResponse()
Also BeginGetResponse(AsyncCallback, Object)BeginGetResponse(AsyncCallback, Object)
Making Asynchronous Requests
FileWebRequest FileWebRequest
I n this Article
Initializes a new instance of the FileWebRequest class from the specified instances of the SerializationInfo and
StreamingContext classes.

[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?


linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
protected FileWebRequest (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.FileWebRequest : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.FileWebRequest

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo object that contains the information that is required to serialize the new FileWebRequest object.
streamingContext StreamingContext StreamingContext
A StreamingContext object that contains the source of the serialized stream that is associated with the new
FileWebRequest object.
Attributes ObsoleteAttribute ObsoleteAttribute

Remarks
This constructor implements the ISerializable interface for the FileWebRequest class.
See XML and SOAP Serialization
Also
FileWebRequest.GetObjectData FileWebRequest.Get
ObjectData
I n this Article
Populates a SerializationInfo with the data needed to serialize the target object.

protected override void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects that are included in the SerializationInfo are automatically tracked and serialized by the formatter.
FileWebRequest.GetRequestStream FileWebRequest.Get
RequestStream
I n this Article
Returns a Stream object for writing data to the file system resource.

public override System.IO.Stream GetRequestStream ();


override this.GetRequestStream : unit -> System.IO.Stream

Returns
Stream Stream
A Stream for writing data to the file system resource.
Exceptions
WebException WebException
The request times out.

Examples
The following code example uses the GetRequestStream method to obtain a stream instance used to write to the file.
Refer to the complete example in the FileWebRequest class.
// Enter the string to write to the file.
Console.WriteLine ("Enter the string you want to write:");

string userInput = Console.ReadLine ();

// Convert the string to a byte array.


ASCIIEncoding encoder = new ASCIIEncoding ();
byte[] byteArray = encoder.GetBytes (userInput);

// Set the ContentLength property.


myFileWebRequest.ContentLength = byteArray.Length;

string contentLength = myFileWebRequest.ContentLength.ToString ();

Console.WriteLine ("
The content length is {0}.", contentLength);

// Get the file stream handler to write to the file.


Stream readStream = myFileWebRequest.GetRequestStream ();

// Write to the file stream.


// Note. For this to work, the file must be accessible
// on the network. This can be accomplished by setting the property
// sharing of the folder containg the file.
// FileWebRequest.Credentials property cannot be used for this purpose.
readStream.Write (byteArray, 0, userInput.Length);
Console.WriteLine ("
The String you entered was successfully written to the file.");

Remarks
The GetRequestStream method provides synchronous access to the Stream. For asynchronous access, use the
BeginGetRequestStream and EndGetRequestStream methods.
See BeginGetRequestStream(AsyncCallback, Object)BeginGetRequestStream(AsyncCallback, Object)
Also
FileWebRequest.GetRequestStreamAsync FileWeb
Request.GetRequestStreamAsync
I n this Article
public override System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync ();
override this.GetRequestStreamAsync : unit -> System.Threading.Tasks.Task<System.IO.Stream>

Returns
Task<Stream>
FileWebRequest.GetResponse FileWebRequest.Get
Response
I n this Article
Returns a response to a file system request.

public override System.Net.WebResponse GetResponse ();


override this.GetResponse : unit -> System.Net.WebResponse

Returns
WebResponse WebResponse
A WebResponse that contains the response from the file system resource.
Exceptions
WebException WebException
The request timed out.

Examples
The following code example uses the GetResponse method to return a file system request response.
//
// This example shows how to use the FileWebRequest.GetResponse method
// to read and display the contents of a file passed by the user.
// Note. For this program to work, the folder containing the test file
// must be shared, with its permissions set to allow read access.

using System;
using System.Net;
using System.IO;

namespace Mssc.PluggableProtocols.File
{

class TestGetResponse
{
private static FileWebResponse myFileWebResponse;

private static void showUsage()


{
Console.WriteLine("
Please enter file name:");
Console.WriteLine("Usage: cs_getresponse <systemname>/<sharedfoldername>/<filename>");
}

private static bool makeFileRequest(string fileName)


{
bool requestOk = false;
try
{
Uri myUrl = new Uri("file://" + fileName);

// Create a FileWebRequest object using the passed URI.


FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(myUrl);

// Get the FileWebResponse object.


myFileWebResponse =(FileWebResponse)myFileWebRequest.GetResponse();
requestOk = true;
}
catch(WebException e)
{
Console.WriteLine("WebException: "+e.Message);
}
catch(UriFormatException e)
{
Console.WriteLine("UriFormatWebException: "+e.Message);
}

return requestOk;

private static void readFile()


{
try
{
// Create the file stream.
Stream receiveStream=myFileWebResponse.GetResponseStream();

// Create a reader object to read the file content.


StreamReader readStream = new StreamReader( receiveStream );

// Create a local buffer for a temporary storage of the


// read data.
char[] readBuffer = new Char[256];

// Read the first 256 bytes.


int count = readStream.Read( readBuffer, 0, 256 );

Console.WriteLine("The file content is:");


Console.WriteLine("");

// Loop to read the remaining data in blocks of 256 bytes


// and display the data on the console.
while (count > 0)
{
String str = new String(readBuffer, 0, count);
Console.WriteLine(str+"
");
count = readStream.Read(readBuffer, 0, 256);
}

readStream.Close();

// Release the response object resources.


myFileWebResponse.Close();

}
catch(WebException e)
{
Console.WriteLine("The WebException: "+e.Message);
}
catch(UriFormatException e)
{
Console.WriteLine("The UriFormatException: "+e.Message);
}

static void Main(string[] args)


{

if (args.Length < 1)
if (args.Length < 1)
showUsage();
else
{
if (makeFileRequest(args[0])== true)
readFile();
}
}
}
}

Remarks
The GetResponse method returns a WebResponse object that contains the response from the file system resource.
The GetResponse method provides synchronous access to the WebResponse. For asynchronous access, use the
BeginGetResponse and EndGetResponse methods.
FileWebRequest.GetResponseAsync FileWebRequest.Get
ResponseAsync
I n this Article
public override System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync ();
override this.GetResponseAsync : unit -> System.Threading.Tasks.Task<System.Net.WebResponse>

Returns
Task<WebResponse>
FileWebRequest.Headers FileWebRequest.Headers
I n this Article
Gets a collection of the name/value pairs that are associated with the request. This property is reserved for future use.
public override System.Net.WebHeaderCollection Headers { get; }
member this.Headers : System.Net.WebHeaderCollection

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection that contains header name/value pairs associated with this request.

Remarks
The Headers property is currently not used by the FileWebRequest class.
FileWebRequest.ISerializable.GetObjectData
I n this Article
Populates a SerializationInfo object with the required data to serialize the FileWebRequest.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
A SerializationInfo that holds the serialized data for the FileWebRequest.
streamingContext StreamingContext
A StreamingContext that contains the destination of the serialized stream that is associated with the new
FileWebRequest.
FileWebRequest.Method FileWebRequest.Method
I n this Article
Gets or sets the protocol method used for the request. This property is reserved for future use.
public override string Method { get; set; }
member this.Method : string with get, set

Returns
String String
The protocol method to use in this request.
Exceptions
ArgumentException ArgumentException
The method is invalid.
-or-
The method is not supported.
-or-
Multiple methods were specified.

Examples
The following code example sets the protocol method used for the request. Refer to the complete example in the
FileWebRequest class.
// Create a Uri object.
Uri myUrl = new Uri ("file://" + fileName);

// Create a FileWebRequest object.


myFileWebRequest = (FileWebRequest)WebRequest.CreateDefault (myUrl);

// Set the time-out to the value selected by the user.


myFileWebRequest.Timeout = timeout;

// Set the Method property to POST


myFileWebRequest.Method = "POST";

Remarks
The Method property is currently not used by the FileWebRequest class.
FileWebRequest.PreAuthenticate FileWebRequest.Pre
Authenticate
I n this Article
Gets or sets a value that indicates whether to preauthenticate a request. This property is reserved for future use.

public override bool PreAuthenticate { get; set; }


member this.PreAuthenticate : bool with get, set

Returns
Boolean Boolean
true to preauthenticate; otherwise, false .

Remarks
The PreAuthenticate property is currently not used by the FileWebRequest class.
FileWebRequest.Proxy FileWebRequest.Proxy
I n this Article
Gets or sets the network proxy to use for this request. This property is reserved for future use.
public override System.Net.IWebProxy Proxy { get; set; }
member this.Proxy : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
An IWebProxy that indicates the network proxy to use for this request.

Remarks
The Proxy property is currently not used by the FileWebRequest class.
FileWebRequest.RequestUri FileWebRequest.RequestUri
I n this Article
Gets the Uniform Resource Identifier (URI) of the request.
public override Uri RequestUri { get; }
member this.RequestUri : Uri

Returns
Uri Uri
A Uri that contains the URI of the request.

Examples
The following code example uses the RequestUri property to get the URI of the request.
// Compare the file name and 'RequestUri' is same or not.
if(myFileWebRequest.RequestUri.Equals(myUrl))
{
// 'GetRequestStream' method returns the stream handler for writing into the file.
Stream readStream =myFileWebRequest.GetRequestStream();
// Write to the stream
readStream.Write(byteArray,0,userInput.Length);
readStream.Close();
}

Console.WriteLine("
The String you entered was successfully written into the file.");
Console.WriteLine("The content length sent to the server is "+myFileWebRequest.ContentLength+".");
FileWebRequest.Timeout FileWebRequest.Timeout
I n this Article
Gets or sets the length of time until the request times out.
public override int Timeout { get; set; }
member this.Timeout : int with get, set

Returns
Int32 Int32
The time, in milliseconds, until the request times out, or the value Infinite to indicate that the request does not time out.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified is less than or equal to zero and is not Infinite.

Examples
The following code example sets the Timeout property. Refer to the complete example in the FileWebRequest class.
// Create a Uri object.
Uri myUrl = new Uri ("file://" + fileName);

// Create a FileWebRequest object.


myFileWebRequest = (FileWebRequest)WebRequest.CreateDefault (myUrl);

// Set the time-out to the value selected by the user.


myFileWebRequest.Timeout = timeout;

Remarks
A Domain Name System (DNS ) query may take up to 15 seconds to return or time out. If your request contains a host
name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more
before a WebException is thrown to indicate a time-out on your request.
FileWebRequest.UseDefaultCredentials FileWebRequest.
UseDefaultCredentials
I n this Article
Always throws a NotSupportedException.

public override bool UseDefaultCredentials { get; set; }


member this.UseDefaultCredentials : bool with get, set

Returns
Boolean Boolean
Always throws a NotSupportedException.
Exceptions
NotSupportedException NotSupportedException
Default credentials are not supported for file Uniform Resource Identifiers (URIs).

Remarks
The UseDefaultCredentials property is provided only for compatibility with other implementations of the WebRequest
and WebResponse classes. There is no reason to use UseDefaultCredentials.
FileWebResponse FileWebResponse Class
Provides a file system implementation of the WebResponse class.

D eclaration
[System.Serializable]
public class FileWebResponse : System.Net.WebResponse,
System.Runtime.Serialization.ISerializable
type FileWebResponse = class
inherit WebResponse
interface ISerializable

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
WebResponse WebResponse

Remarks
The FileWebResponse class implements the WebResponse abstract base class to return file system resources for the
FileWebRequest class.
Client applications do not create FileWebResponse instances directly; instead, they are created by calling the
GetResponse method on a FileWebRequest instance.
The GetResponseStream method returns a Stream instance that provides read-only access to a file system resource.
The FileWebResponse class relies on the File class for error handling and code access security.

Constructors
FileWebResponse(SerializationInfo, StreamingContext)
FileWebResponse(SerializationInfo, StreamingContext)

Initializes a new instance of the FileWebResponse class from the specified instances of the SerializationInfo and
StreamingContext classes.

Properties
ContentLength
ContentLength

Gets the length of the content in the file system resource.

ContentType
ContentType

Gets the content type of the file system resource.


Headers
Headers

Gets a collection of header name/value pairs associated with the response.

ResponseUri
ResponseUri

Gets the URI of the file system resource that provided the response.

SupportsHeaders
SupportsHeaders

Gets a value that indicates whether the Headers property is supported by the FileWebResponse instance.

Methods
Close()
Close()

Closes the response stream.

Dispose(Boolean)
Dispose(Boolean)

Releases the unmanaged resources used by the FileWebResponse and optionally releases the managed resources.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

GetResponseStream()
GetResponseStream()

Returns the data stream from the file system resource.

IDisposable.Dispose()
IDisposable.Dispose()

Releases all resources used by the FileWebResponse.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo instance with the data needed to serialize the FileWebResponse.
FileWebResponse.Close FileWebResponse.Close
I n this Article
Closes the response stream.
public override void Close ();
override this.Close : unit -> unit

Examples
The following example uses the Close method to close the response stream.

public static void GetPage(String url)


{
try
{
Uri fileUrl = new Uri("file://"+url);
// Create a FileWebrequest with the specified Uri.
FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
// Send the 'fileWebRequest' and wait for response.
FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
// Process the response here.
Console.WriteLine("
Response Received.Trying to Close the response stream..");
// Release resources of response object.
myFileWebResponse.Close();
Console.WriteLine("
Response Stream successfully closed.");
}
catch(WebException e)
{
Console.WriteLine("\r
WebException thrown.The Reason for failure is : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
The Close method cleans up the resources used by a FileWebResponse and closes the response stream by calling the
Stream.Close method.
Note

The response stream must be closed to avoid running out of system resources. You can closes the response stream by
calling either Stream.Close or Close
FileWebResponse.ContentLength FileWebResponse.
ContentLength
I n this Article
Gets the length of the content in the file system resource.

public override long ContentLength { get; }


member this.ContentLength : int64

Returns
Int64 Int64
The number of bytes returned from the file system resource.

Examples
The following example uses the ContentLength property to obtain the content length of the file system resource.
public static void GetPage(String url)
{
try
{
Uri fileUrl = new Uri("file://"+url);
// Create a 'FileWebrequest' object with the specified Uri.
FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
// Send the 'fileWebRequest' and wait for response.
FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
// Print the ContentLength and ContentType properties received as headers in the response
object.
Console.WriteLine("
Content length :{0}, Content Type :
{1}",myFileWebResponse.ContentLength,myFileWebResponse.ContentType);
// Release resources of response object.
myFileWebResponse.Close();
}
catch(WebException e)
{
Console.WriteLine("\r
WebException thrown.The Reason for failure is : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
The ContentLength property contains the length, in bytes, of the file system resource.
FileWebResponse.ContentType FileWebResponse.
ContentType
I n this Article
Gets the content type of the file system resource.

public override string ContentType { get; }


member this.ContentType : string

Returns
String String
The value "binary/octet-stream".

Examples
The following example uses the ContentType property to obtain the content type of the file system resource.
public static void GetPage(String url)
{
try
{
Uri fileUrl = new Uri("file://"+url);
// Create a 'FileWebrequest' object with the specified Uri.
FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
// Send the 'fileWebRequest' and wait for response.
FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
// Print the ContentLength and ContentType properties received as headers in the response
object.
Console.WriteLine("
Content length :{0}, Content Type :
{1}",myFileWebResponse.ContentLength,myFileWebResponse.ContentType);
// Release resources of response object.
myFileWebResponse.Close();
}
catch(WebException e)
{
Console.WriteLine("\r
WebException thrown.The Reason for failure is : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
The ContentType property contains the content type of the file system resource. The value of ContentType is always
"binary/octet-stream".
FileWebResponse.Dispose FileWebResponse.Dispose
I n this Article
Releases the unmanaged resources used by the FileWebResponse and optionally releases the managed resources.
protected virtual void Dispose (bool disposing);
abstract member Dispose : bool -> unit
override this.Dispose : bool -> unit

Parameters
disposing Boolean Boolean
FileWebResponse FileWebResponse
I n this Article
Initializes a new instance of the FileWebResponse class from the specified instances of the SerializationInfo and
StreamingContext classes.

[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?


linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
protected FileWebResponse (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.FileWebResponse : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.FileWebResponse

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo instance that contains the information required to serialize the new FileWebResponse instance.
streamingContext StreamingContext StreamingContext
An instance of the StreamingContext class that contains the source of the serialized stream associated with the new
FileWebResponse instance.
Attributes ObsoleteAttribute ObsoleteAttribute

Remarks
This constructor implements the ISerializable interface for the FileWebResponse class.
See XML and SOAP Serialization
Also
FileWebResponse.GetObjectData FileWebResponse.Get
ObjectData
I n this Article
Populates a SerializationInfo with the data needed to serialize the target object.

protected override void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
FileWebResponse.GetResponseStream FileWebResponse.
GetResponseStream
I n this Article
Returns the data stream from the file system resource.

public override System.IO.Stream GetResponseStream ();


override this.GetResponseStream : unit -> System.IO.Stream

Returns
Stream Stream
A Stream for reading data from the file system resource.

Examples
The following example uses the GetResponseStream method to return the data stream from the file system resource.
Uri fileUrl = new Uri("file://"+url);
// Create a 'FileWebrequest' object with the specified Uri.
FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
// Send the 'FileWebRequest' object and wait for response.
FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();

// Get the stream object associated with the response object.


Stream receiveStream = myFileWebResponse.GetResponseStream();

Encoding encode = System.Text.Encoding.GetEncoding("utf-8");


// Pipe the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r
Response stream received");

Char[] read = new Char[256];


// Read 256 characters at a time.
int count = readStream.Read( read, 0, 256 );
Console.WriteLine("File Data...\r
");
while (count > 0)
{
// Dump the 256 characters on a string and display the string onto the console.
String str = new String(read, 0, count);
Console.Write(str);
count = readStream.Read(read, 0, 256);
}
Console.WriteLine("");
// Release resources of stream object.
readStream.Close();
// Release resources of response object.
myFileWebResponse.Close();

Remarks
The GetResponseStream method returns the data stream from the file system resource.
Note

The response stream must be closed to avoid running out of system resources. The response stream can be closed by
calling Stream.Close or Close
FileWebResponse.Headers FileWebResponse.Headers
I n this Article
Gets a collection of header name/value pairs associated with the response.
public override System.Net.WebHeaderCollection Headers { get; }
member this.Headers : System.Net.WebHeaderCollection

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection that contains the header name/value pairs associated with the response.

Examples
The following example uses the Headers property to retrieve the name/value pairs associated with the response.
public static void GetPage(String url)
{
try
{
Uri fileUrl = new Uri("file://"+url);
// Create a 'FileWebrequest' object with the specified Uri .
FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create(fileUrl);
// Send the 'fileWebRequest' and wait for response.
FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse();
// Display all Headers present in the response received from the Uri.
Console.WriteLine("\r
The following headers were received in the response:");
// Display each header and the key of the response object.
for(int i=0; i < myFileWebResponse.Headers.Count; ++i)
Console.WriteLine("
Header Name:{0}, Header value :{1}",myFileWebResponse.Headers.Keys[i],
myFileWebResponse.Headers[i]);
myFileWebResponse.Close();
}
catch(WebException e)
{
Console.WriteLine("\r
WebException thrown.The Reason for failure is : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
The Headers property contains two name/value pairs, one for content length and one for content type, both of which
are also exposed as properties, ContentLength and ContentType.
FileWebResponse.IDisposable.Dispose
I n this Article
Releases all resources used by the FileWebResponse.
void IDisposable.Dispose ();

Remarks
Call Dispose() when you are finished using the FileWebResponse. The Dispose() method leaves the FileWebResponse
in an unusable state. After calling Dispose(), you must release all references to the FileWebResponse so the garbage
collector can reclaim the memory that the FileWebResponse was occupying. For more information, see Cleaning Up
Unmanaged Resources and Implementing a Dispose Method.
Note

Always call Dispose() before you release your last reference to the FileWebResponse. Otherwise, the resources it is
using will not be freed until the garbage collector calls the FileWebResponse object's Finalize method.
FileWebResponse.ISerializable.GetObjectData
I n this Article
Populates a SerializationInfo instance with the data needed to serialize the FileWebResponse.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
A SerializationInfo , which will hold the serialized data for the FileWebResponse.
streamingContext StreamingContext
A StreamingContext containing the destination of the serialized stream associated with the new FileWebResponse.
FileWebResponse.ResponseUri FileWebResponse.
ResponseUri
I n this Article
Gets the URI of the file system resource that provided the response.

public override Uri ResponseUri { get; }


member this.ResponseUri : Uri

Returns
Uri Uri
A Uri that contains the URI of the file system resource that provided the response.

Examples
The following example uses the ResponseUri to retrieve the URI of the file system resource that provided the response.
public static void GetPage (String url)
{
try
{
Uri fileUrl = new Uri ("file://" + url);

// Create a 'FileWebrequest' object with the specified Uri .


FileWebRequest myFileWebRequest = (FileWebRequest)WebRequest.Create (fileUrl);

// Send the 'fileWebRequest' and wait for response.


FileWebResponse myFileWebResponse = (FileWebResponse)myFileWebRequest.GetResponse ();

Console.WriteLine ("
The Uri of the file system resource that provided the response is :
{0}

", myFileWebResponse.ResponseUri);

// Release resources of response object.


myFileWebResponse.Close ();
}
catch (WebException e)
{
Console.WriteLine ("\r
WebException thrown.The Reason for failure is : {0}", e.Status);
}
catch (Exception e)
{
Console.WriteLine ("
The following Exception was raised : {0}", e.Message);
}
}

Remarks
The ResponseUri property contains the URI of the file system resource that provided the response. This is always the
file system resource that was requested.
FileWebResponse.SupportsHeaders FileWebResponse.
SupportsHeaders
I n this Article
Gets a value that indicates whether the Headers property is supported by the FileWebResponse instance.

public override bool SupportsHeaders { get; }


member this.SupportsHeaders : bool

Returns
Boolean Boolean
true if the Headers property is supported by the FileWebResponse instance; otherwise, false .

Remarks
This property is always true for .NET Framework 4.5.
FtpStatusCode FtpStatusCode Enum
Specifies the status codes returned for a File Transfer Protocol (FTP ) operation.

D eclaration
public enum FtpStatusCode
type FtpStatusCode =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The FtpStatusCode enumeration defines the values returned in the StatusCode property.
For additional information about FTP server status codes, see RFC 959: "File Transfer Protocol", Section 4.2: "FTP
Replies".

Fields
AccountNeeded AccountNeeded Specifies that a user account on the server is required.

ActionAbortedLocalProcessingError Specifies that an error occurred that prevented the request action from
ActionAbortedLocalProcessingError completing.

ActionAbortedUnknownPageType Specifies that the requested action cannot be taken because the specified page
ActionAbortedUnknownPageType type is unknown. Page types are described in RFC 959 Section 3.1.2.3

ActionNotTakenFilenameNotAllowed Specifies that the requested action cannot be performed on the specified file.
ActionNotTakenFilenameNotAllowed

ActionNotTakenFileUnavailable Specifies that the requested action cannot be performed on the specified file
ActionNotTakenFileUnavailable because the file is not available.

ActionNotTakenFileUnavailableOrBusy Specifies that the requested action cannot be performed on the specified file
ActionNotTakenFileUnavailableOrBusy because the file is not available or is being used.

ActionNotTakenInsufficientSpace Specifies that the requested action cannot be performed because there is not
ActionNotTakenInsufficientSpace enough space on the server.
ArgumentSyntaxError Specifies that one or more command arguments has a syntax error.
ArgumentSyntaxError

BadCommandSequence Specifies that the sequence of commands is not in the correct order.
BadCommandSequence

CantOpenData CantOpenData Specifies that the data connection cannot be opened.

ClosingControl ClosingControl Specifies that the server is closing the control connection.

ClosingData ClosingData Specifies that the server is closing the data connection and that the requested
file action was successful.

CommandExtraneous Specifies that the command is not implemented by the server because it is not
CommandExtraneous needed.

CommandNotImplemented Specifies that the command is not implemented by the FTP server.
CommandNotImplemented

CommandOK CommandOK Specifies that the command completed successfully.

CommandSyntaxError Specifies that the command has a syntax error or is not a command
CommandSyntaxError recognized by the server.

ConnectionClosed ConnectionClosed Specifies that the connection has been closed.

DataAlreadyOpen DataAlreadyOpen Specifies that the data connection is already open and the requested transfer is
starting.

DirectoryStatus DirectoryStatus Specifies the status of a directory.

EnteringPassive EnteringPassive Specifies that the server is entering passive mode.

FileActionAborted Specifies that the requested action cannot be performed.


FileActionAborted

FileActionOK FileActionOK Specifies that the requested file action completed successfully.
FileCommandPending Specifies that the requested file action requires additional information.
FileCommandPending

FileStatus FileStatus Specifies the status of a file.

LoggedInProceed LoggedInProceed Specifies that the user is logged in and can send commands.

NeedLoginAccount NeedLoginAccount Specifies that the server requires a login account to be supplied.

NotLoggedIn NotLoggedIn Specifies that login information must be sent to the server.

OpeningData OpeningData Specifies that the server is opening the data connection.

PathnameCreated PathnameCreated Specifies that the requested path name was created.

RestartMarker RestartMarker Specifies that the response contains a restart marker reply. The text of the
description that accompanies this status contains the user data stream marker
and the server marker.

SendPasswordCommand Specifies that the server expects a password to be supplied.


SendPasswordCommand

SendUserCommand SendUserCommand Specifies that the server is ready for a user login operation.

ServerWantsSecureSession Specifies that the server accepts the authentication mechanism specified by
ServerWantsSecureSession the client, and the exchange of security data is complete.

ServiceNotAvailable Specifies that the service is not available.


ServiceNotAvailable

ServiceTemporarilyNotAvailable Specifies that the service is not available now; try your request later.
ServiceTemporarilyNotAvailable

SystemType SystemType Specifies the system type name using the system names published in the
Assigned Numbers document published by the Internet Assigned Numbers
Authority.

Undefined Undefined Included for completeness, this value is never returned by servers.
FtpWebRequest FtpWebRequest Class
Implements a File Transfer Protocol (FTP ) client.

D eclaration
public sealed class FtpWebRequest : System.Net.WebRequest
type FtpWebRequest = class
inherit WebRequest

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
WebRequest WebRequest

Remarks
Im p o rt a nt

We don't recommend that you use the FtpWebRequest class for new development. For more information and
alternatives to FtpWebRequest , see WebRequest shouldn't be used on GitHub.
To obtain an instance of FtpWebRequest, use the Create method. You can also use the WebClient class to upload and
download information from an FTP server. Using either of these approaches, when you specify a network resource that
uses the FTP scheme (for example, "ftp://contoso.com" ) the FtpWebRequest class provides the ability to
programmatically interact with FTP servers.
The URI may be relative or absolute. If the URI is of the form "ftp://contoso.com/%2fpath" (%2f is an escaped '/'),
then the URI is absolute, and the current directory is /path . If, however, the URI is of the form
"ftp://contoso.com/path" , first the .NET Framework logs into the FTP server (using the user name and password
set by the Credentials property), then the current directory is set to <UserLoginDirectory>/path .
You must have a valid user name and password for the server or the server must allow anonymous logon. You can
specify the credentials used to connect to the server by setting the Credentials property or you can include them in the
UserInfo portion of the URI passed to the Create method. If you include UserInfo information in the URI, the
Credentials property is set to a new network credential with the specified user name and password information.
Cautio n

Unless the EnableSsl property is true , all data and commands, including your user name and password information,
are sent to the server in clear text. Anyone monitoring network traffic can view your credentials and use them to
connect to the server. If you are connecting to an FTP server that requires credentials and supports Secure Sockets
Layer (SSL ), you should set EnableSsl to true .
You must have WebPermission to access the FTP resource; otherwise, a SecurityException exception is thrown.
Specify the FTP command to send to the server by setting the Method property to a value defined in the
WebRequestMethods.Ftp structure. To transmit text data, change the UseBinary property from its default value ( true )
to false . For details and restrictions, see Method.
When using an FtpWebRequest object to upload a file to a server, you must write the file content to the request stream
obtained by calling the GetRequestStream method or its asynchronous counterparts, the BeginGetRequestStream and
EndGetRequestStream methods. You must write to the stream and close the stream before sending the request.
Requests are sent to the server by calling the GetResponse method or its asynchronous counterparts, the
BeginGetResponse and EndGetResponse methods. When the requested operation completes, an FtpWebResponse
object is returned. The FtpWebResponse object provides the status of the operation and any data downloaded from the
server.
You can set a time-out value for reading or writing to the server by using the ReadWriteTimeout property. If the time-
out period is exceeded, the calling method throws a WebException with WebExceptionStatus set to Timeout.
When downloading a file from an FTP server, if the command was successful, the contents of the requested file are
available in the response object's stream. You can access this stream by calling the GetResponseStream method. For
more information, see FtpWebResponse.
If the Proxy property is set, either directly or in a configuration file, communications with the FTP server are made
through the specified proxy. If the specified proxy is an HTTP proxy, only the DownloadFile, ListDirectory, and
ListDirectoryDetails commands are supported.
Only downloaded binary content is cached; that is, content received using the DownloadFile command with the
UseBinary property set to true .

Multiple FtpWebRequests reuse existing connections, if possible.


For more information about the FTP protocol, see RFC 959: File Transfer Protocol.

Properties
ClientCertificates
ClientCertificates

Gets or sets the certificates used for establishing an encrypted connection to the FTP server.

ConnectionGroupName
ConnectionGroupName

Gets or sets the name of the connection group that contains the service point used to send the current request.

ContentLength
ContentLength

Gets or sets a value that is ignored by the FtpWebRequest class.

ContentOffset
ContentOffset

Gets or sets a byte offset into the file being downloaded by this request.

ContentType
ContentType

Always throws a NotSupportedException.

Credentials
Credentials

Gets or sets the credentials used to communicate with the FTP server.

DefaultCachePolicy
DefaultCachePolicy

Defines the default cache policy for all FTP requests.

EnableSsl
EnableSsl

Gets or sets a Boolean that specifies that an SSL connection should be used.

Headers
Headers

Gets an empty WebHeaderCollection object.

KeepAlive
KeepAlive

Gets or sets a Boolean value that specifies whether the control connection to the FTP server is closed after the
request completes.

Method
Method

Gets or sets the command to send to the FTP server.

PreAuthenticate
PreAuthenticate

Always throws a NotSupportedException.

Proxy
Proxy

Gets or sets the proxy used to communicate with the FTP server.

ReadWriteTimeout
ReadWriteTimeout

Gets or sets a time-out when reading from or writing to a stream.


RenameTo
RenameTo

Gets or sets the new name of a file being renamed.

RequestUri
RequestUri

Gets the URI requested by this instance.

ServicePoint
ServicePoint

Gets the ServicePoint object used to connect to the FTP server.

Timeout
Timeout

Gets or sets the number of milliseconds to wait for a request.

UseBinary
UseBinary

Gets or sets a Boolean value that specifies the data type for file transfers.

UseDefaultCredentials
UseDefaultCredentials

Always throws a NotSupportedException.

UsePassive
UsePassive

Gets or sets the behavior of a client application's data transfer process.

Methods
Abort()
Abort()

Terminates an asynchronous FTP operation.

BeginGetRequestStream(AsyncCallback, Object)
BeginGetRequestStream(AsyncCallback, Object)

Begins asynchronously opening a request's content stream for writing.


BeginGetResponse(AsyncCallback, Object)
BeginGetResponse(AsyncCallback, Object)

Begins sending a request and receiving a response from an FTP server asynchronously.

EndGetRequestStream(IAsyncResult)
EndGetRequestStream(IAsyncResult)

Ends a pending asynchronous operation started with BeginGetRequestStream(AsyncCallback, Object).

EndGetResponse(IAsyncResult)
EndGetResponse(IAsyncResult)

Ends a pending asynchronous operation started with BeginGetResponse(AsyncCallback, Object).

GetRequestStream()
GetRequestStream()

Retrieves the stream used to upload data to an FTP server.

GetResponse()
GetResponse()

Returns the FTP server response.

See Also
WebRequest WebRequest
WebResponse WebResponse
FtpWebRequest.Abort FtpWebRequest.Abort
I n this Article
Terminates an asynchronous FTP operation.
public override void Abort ();
override this.Abort : unit -> unit

Examples
The following code example demonstrates how the user can terminate an asynchronous upload of a file from the local
directory to the server.
public class ApplicationMain
{
public static void Main()
{
ManualResetEvent wait = new ManualResetEvent(false);
AsynchronousFtpUpLoader uploader = new AsynchronousFtpUpLoader(wait);
uploader.AllowAbortUpload("out.txt", "ftp://sharriso1/ftptests.txt");
wait.WaitOne();
if (uploader.AsyncException != null)
{
Console.WriteLine(uploader.AsyncException.ToString());
}
}
}
public class AsynchronousFtpUpLoader
{
ManualResetEvent wait;
FtpWebRequest request;
byte [] fileContents;
Exception asyncException = null;

public AsynchronousFtpUpLoader(ManualResetEvent wait)


{
this.wait = wait;
}

public Exception AsyncException


{
get { return asyncException;}
}

private void EndGetStreamCallback(IAsyncResult ar)


{
Stream requestStream = null;
// End the asynchronous call to get the request stream.
try
{
requestStream = request.EndGetRequestStream(ar);
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine("Could not get the request stream.");
asyncException = e;
wait.Set();
return;
}
// Write the file contents to the request stream.
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Write(fileContents, 0, fileContents.Length);
Console.WriteLine ("Writing {0} bytes to the stream.", fileContents.Length);
// IMPORTANT: Close the request stream before sending the request.
requestStream.Close();
}

// The EndGetResponseCallback method


// completes a call to BeginGetResponse.
private void EndGetResponseCallback(IAsyncResult ar)
{
FtpWebResponse response = null;
try
{
response = (FtpWebResponse) request.EndGetResponse(ar);
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine ("Error getting response.");
asyncException = e;
wait.Set();
}
Console.WriteLine("Upload status: {0}",response.StatusDescription);
// Signal the application thread that this operation is complete.
wait.Set();
}
internal void AbortRequest(FtpWebRequest request)
{
request.Abort();
Console.WriteLine("Request aborted!");
wait.Set();
}

public void AllowAbortUpload(string fileName, string serverUri)


{
request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.UploadFile;
// Get the file to be uploaded and convert it to bytes.
StreamReader sourceStream = new StreamReader(fileName);
fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
// Set the content length to the number of bytes in the file.
request.ContentLength = fileContents.Length;
// Asynchronously get the stream for the file contents.
IAsyncResult ar = request.BeginGetRequestStream(
new AsyncCallback (EndGetStreamCallback), null);
while (!ar.IsCompleted)
{
Console.WriteLine("Press 'a' to abort writing to the request stream. Press any other
key to continue...");
string input = Console.ReadLine();
if (input == "a")
{
AbortRequest(request);
return;
}
}
Console.WriteLine("Sending the request asynchronously...");
IAsyncResult responseAR = request.BeginGetResponse(
new AsyncCallback (EndGetResponseCallback), null);

while (!responseAR.IsCompleted)
{
Console.WriteLine("Press 'a' to abort the upload. Press any other key to
continue.");
continue.");
string input = Console.ReadLine();
if (input == "a")
{
AbortRequest(request);
return;
}
}
}

Remarks
If there is no operation in progress, this method does nothing. If a file transfer is in progress, this method terminates
the transfer.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.BeginGetRequestStream FtpWeb
Request.BeginGetRequestStream
I n this Article
Begins asynchronously opening a request's content stream for writing.

public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state);


override this.BeginGetRequestStream : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
state Object Object
A user-defined object that contains information about the operation. This object is passed to the callback delegate
when the operation completes.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that indicates the status of the operation.
Exceptions
InvalidOperationException InvalidOperationException
A previous call to this method or GetRequestStream() has not yet completed.
WebException WebException
A connection to the FTP server could not be established.
ProtocolViolationException ProtocolViolationException
The Method property is not set to UploadFile.

Examples
The following code example demonstrates beginning an asynchronous operation to get a request's stream. This code
example is part of a larger example provided for the FtpWebRequest class overview.
// Command line arguments are two strings:
// 1. The url that is the name of the file being uploaded to the server.
// 2. The name of the file on the local machine.
//
public static void Main(string[] args)
{
// Create a Uri instance with the specified URI string.
// If the URI is not correctly formed, the Uri constructor
// will throw an exception.
ManualResetEvent waitObject;

Uri target = new Uri (args[0]);


string fileName = args[1];
FtpState state = new FtpState();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
request.Method = WebRequestMethods.Ftp.UploadFile;

// This example uses anonymous logon.


// The request is anonymous by default; the credential does not have to be specified.
// The example specifies the credential only to
// control how actions are logged on the server.

request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

// Store the request in the object that we pass into the


// asynchronous operations.
state.Request = request;
state.FileName = fileName;

// Get the event to wait on.


waitObject = state.OperationComplete;

// Asynchronously get the stream for the file contents.


request.BeginGetRequestStream(
new AsyncCallback (EndGetStreamCallback),
state
);

// Block the current thread until all operations are complete.


waitObject.WaitOne();

// The operations either completed or threw an exception.


if (state.OperationException != null)
{
throw state.OperationException;
}
else
{
Console.WriteLine("The operation completed - {0}", state.StatusDescription);
}
}

Remarks
You must complete the asynchronous operation by calling the EndGetRequestStream method. Typically,
EndGetRequestStream is called by the method referenced by callback . To determine the state of the operation, check
the properties in the IAsyncResult object returned by this method.
This method does not block while waiting for the stream. To block, call GetRequestStream in place of this method.
For detailed information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.BeginGetResponse FtpWebRequest.
BeginGetResponse
I n this Article
Begins sending a request and receiving a response from an FTP server asynchronously.

public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state);


override this.BeginGetResponse : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
state Object Object
A user-defined object that contains information about the operation. This object is passed to the callback delegate
when the operation completes.
Returns
IAsyncResult IAsyncResult
An IAsyncResult instance that indicates the status of the operation.
Exceptions
InvalidOperationException InvalidOperationException
GetResponse() or BeginGetResponse(AsyncCallback, Object) has already been called for this instance.

Examples
The following code example demonstrates ending an asynchronous operation to get a request's stream, and then
starting a request to get the response. This code example is part of a larger example provided for the FtpWebRequest
class overview.
private static void EndGetStreamCallback(IAsyncResult ar)
{
FtpState state = (FtpState) ar.AsyncState;

Stream requestStream = null;


// End the asynchronous call to get the request stream.
try
{
requestStream = state.Request.EndGetRequestStream(ar);
// Copy the file contents to the request stream.
const int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
int count = 0;
int readBytes = 0;
FileStream stream = File.OpenRead(state.FileName);
do
{
readBytes = stream.Read(buffer, 0, bufferLength);
requestStream.Write(buffer, 0, readBytes);
count += readBytes;
}
while (readBytes != 0);
Console.WriteLine ("Writing {0} bytes to the stream.", count);
// IMPORTANT: Close the request stream before sending the request.
requestStream.Close();
// Asynchronously get the response to the upload request.
state.Request.BeginGetResponse(
new AsyncCallback (EndGetResponseCallback),
state
);
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine("Could not get the request stream.");
state.OperationException = e;
state.OperationComplete.Set();
return;
}

Remarks
You must complete the asynchronous operation by calling the EndGetResponse method. Typically, EndGetResponse is
called by the method referenced by callback . To determine the state of the operation, check the properties in the
IAsyncResult object returned by the BeginGetResponse method.
If the Proxy property is set, either directly or in a configuration file, communications with the FTP server are made
through the specified proxy.
BeginGetResponse does not block while waiting for the response from the server. To block, call the GetResponse
method in place of BeginGetResponse.
For more information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
Note

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from
the server.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.ClientCertificates FtpWebRequest.Client
Certificates
I n this Article
Gets or sets the certificates used for establishing an encrypted connection to the FTP server.

public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates {


get; set; }
member this.ClientCertificates :
System.Security.Cryptography.X509Certificates.X509CertificateCollection with get, set

Returns
X509CertificateCollection X509CertificateCollection
An X509CertificateCollection object that contains the client certificates.
Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation is null .

Remarks
Client certificates are used to authenticate the client during the initial SSL connection negotiation. For more
information, see EnableSsl.
Note

The .NET Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new
request, if possible. When attempting to reuse an SSL session, the .NET Framework uses the first element of
ClientCertificates (if there is one), or tries to reuse an anonymous session if ClientCertificates is empty.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.ConnectionGroupName FtpWebRequest.
ConnectionGroupName
I n this Article
Gets or sets the name of the connection group that contains the service point used to send the current request.

public override string ConnectionGroupName { get; set; }


member this.ConnectionGroupName : string with get, set

Returns
String String
A String value that contains a connection group name.
Exceptions
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example retrieves the value of this property.
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
Console.WriteLine("Proxy: (none)");
}

Console.WriteLine("ConnectionGroup: {0}",
request.ConnectionGroupName == null ? "none" : request.ConnectionGroupName
);

Remarks
Connection groups associate a set of requests with a particular connection or set of connections. The connections in a
connection group can be reused only by requests originating in the same application domain, when the credentials on
the request are the same and the request specifies the connection group name. When a request does not specify a
connection group name, any existing connection to the requested server that is not associated with a connection group
can be used. When the credentials are not the same, the existing connection is closed and the new request must be
reauthenticated.
Using connection groups can improve performance because this allows all of the requests for a user to reuse the
connection authenticated with the user's credentials.
Changing the ConnectionGroupName property after calling the GetRequestStream, BeginGetRequestStream,
GetResponse, or BeginGetResponse method causes an InvalidOperationException exception.
See WebRequestWebRequest
Also WebResponseWebResponse
Managing Connections
FtpWebRequest.ContentLength FtpWebRequest.Content
Length
I n this Article
Gets or sets a value that is ignored by the FtpWebRequest class.

public override long ContentLength { get; set; }


member this.ContentLength : int64 with get, set

Returns
Int64 Int64
An Int64 value that should be ignored.

Remarks
The ContentLength property is provided only for compatibility with other implementations of the WebRequest and
WebResponse classes. There is no reason to use ContentLength.
FtpWebRequest.ContentOffset FtpWebRequest.Content
Offset
I n this Article
Gets or sets a byte offset into the file being downloaded by this request.

public long ContentOffset { get; set; }


member this.ContentOffset : int64 with get, set

Returns
Int64 Int64
An Int64 instance that specifies the file offset, in bytes. The default value is zero.
Exceptions
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for this property is less than zero.

Examples
The following code example demonstrates downloading part of a file from a server and appending the downloaded
data to a local file.
public static bool RestartDownloadFromServer(string fileName, Uri serverUri, long offset)
{
// The serverUri parameter should use the ftp:// scheme.
// It identifies the server file that is to be downloaded
// Example: ftp://contoso.com/someFile.txt.

// The fileName parameter identifies the local file.


//The serverUri parameter identifies the remote file.
// The offset parameter specifies where in the server file to start reading data.

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.ContentOffset = offset;
FtpWebResponse response = null;
try
{
response = (FtpWebResponse) request.GetResponse();
}
catch (WebException e)
{
Console.WriteLine (e.Status);
Console.WriteLine (e.Message);
return false;
}
// Get the data stream from the response.
Stream newFile = response.GetResponseStream();
// Use a StreamReader to simplify reading the response data.
StreamReader reader = new StreamReader(newFile);
string newFileData = reader.ReadToEnd();
// Append the response data to the local file
// using a StreamWriter.
StreamWriter writer = File.AppendText(fileName);
writer.Write(newFileData);
// Display the status description.

// Cleanup.
writer.Close();
reader.Close();
response.Close();
Console.WriteLine("Download restart - status: {0}",response.StatusDescription);
return true;
}

Remarks
Set the ContentOffset property when downloading a file from an FTP server. This offset indicates the position in the
server's file that marks the start of the data to be downloaded. The offset is specified as the number of bytes from the
start of the file; the offset of the first byte is zero.
Setting ContentOffset causes the FtpWebRequest to send a restart ( REST ) command to the server. This command is
ignored by most FTP server implementations if you are uploading data to the server.
Changing ContentOffset after calling the GetRequestStream, BeginGetRequestStream, GetResponse, or
BeginGetResponse method causes an InvalidOperationException exception.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.ContentType FtpWebRequest.Content
Type
I n this Article
Always throws a NotSupportedException.

public override string ContentType { get; set; }


member this.ContentType : string with get, set

Returns
String String
Always throws a NotSupportedException.
Exceptions
NotSupportedException NotSupportedException
Content type information is not supported for FTP.

Remarks
The ContentType property is provided only for compatibility with other implementations of the WebRequest and
WebResponse classes. There is no reason to use ContentType.
FtpWebRequest.Credentials FtpWebRequest.Credentials
I n this Article
Gets or sets the credentials used to communicate with the FTP server.
public override System.Net.ICredentials Credentials { get; set; }
member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials instance; otherwise, null if the property has not been set.
Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation is null .
ArgumentException ArgumentException
An ICredentials of a type other than NetworkCredential was specified for a set operation.
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example retrieves the value of this property and uses it to display the user name.
Console.WriteLine("User {0} {1}",
request.Credentials.GetCredential(request.RequestUri,"basic").UserName,
request.RequestUri
);

Remarks
You are not required to specify credentials when connecting using anonymous logon. You must set the Credentials
property by using a credential of type NetworkCredential; this ensures that the user name and password can be read
and sent to the server.
Cautio n

Credentials information is not encrypted when transmitted to the server unless the EnableSsl property is set to true .
Changing Credentials after calling the GetRequestStream, BeginGetRequestStream, GetResponse, or
BeginGetResponse method causes an InvalidOperationException exception.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.DefaultCachePolicy FtpWebRequest.
DefaultCachePolicy
I n this Article
Defines the default cache policy for all FTP requests.

public static System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get; set; }


member this.DefaultCachePolicy : System.Net.Cache.RequestCachePolicy with get, set

Returns
RequestCachePolicy RequestCachePolicy
A RequestCachePolicy that defines the cache policy for FTP requests.
Exceptions
ArgumentNullException ArgumentNullException
The caller tried to set this property to null .

Remarks
Only content received using the DownloadFile command is cached.
The following table describes the effects of FTP caching policies on FtpWebRequest.

PO LICY EFFECT

Default Returns the cached resource if the resource is fresh, the


content length is accurate, and the expiration, modification,
and content length attributes are present.

BypassCache Returns the resource from the server.

CacheOnly Returns the cached resource if the content length is present


and matches the entry size; otherwise, throws a
WebException.

CacheIfAvailable Returns the cached resource if the content length is provided


and matches the entry size; otherwise, the resource is
downloaded from the server and is returned to the caller.

Revalidate Returns the cached resource if the timestamp of the cached


resource is the same as the time stamp of the resource on the
server; otherwise, the resource is downloaded from the server,
stored in the cache, and returned to the caller.

Reload Downloads the resource from the server, stores it in the cache,
and returns the resource to the caller.

NoCacheNoStore If a cached resource exists, it is deleted. The resource is


downloaded from the server and is returned to the caller.
Note

Setting DefaultCachePolicy overrides any configuration setting.


See defaultFtpCachePolicy (Network Settings)
Also
FtpWebRequest.EnableSsl FtpWebRequest.EnableSsl
I n this Article
Gets or sets a Boolean that specifies that an SSL connection should be used.
public bool EnableSsl { get; set; }
member this.EnableSsl : bool with get, set

Returns
Boolean Boolean
true if control and data transmissions are encrypted; otherwise, false . The default value is false .
Exceptions
InvalidOperationException InvalidOperationException
The connection to the FTP server has already been established.

Examples
The following code example uses an encrypted connection to download the directory listing from an FTP server.
public static bool ListFilesOnServerSsl(Uri serverUri)
{
// The serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.EnableSsl = true;

// Get the ServicePoint object used for this request, and limit it to one connection.
// In a real-world application you might use the default number of connections (2),
// or select a value that works best for your application.

ServicePoint sp = request.ServicePoint;
Console.WriteLine("ServicePoint connections = {0}.", sp.ConnectionLimit);
sp.ConnectionLimit = 1;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();


Console.WriteLine("The content length is {0}", response.ContentLength);
// The following streams are used to read the data returned from the server.
Stream responseStream = null;
StreamReader readStream = null;
try
{
responseStream = response.GetResponseStream();
readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);

if (readStream != null)
{
// Display the data received from the server.
Console.WriteLine(readStream.ReadToEnd());
}
Console.WriteLine("List status: {0}",response.StatusDescription);
}
finally
{
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
}

Console.WriteLine("Banner message: {0}",


response.BannerMessage);

Console.WriteLine("Welcome message: {0}",


response.WelcomeMessage);

Console.WriteLine("Exit message: {0}",


response.ExitMessage);
return true;
}

Remarks
Cautio n

Unless the EnableSsl property is true , all data and commands, including your user name and password information,
are sent to the server in clear text. Anyone monitoring network traffic can view your credentials and use them to
connect to the server. If you are connecting to an FTP server that requires credentials and supports SSL, you should set
EnableSsl to true .

The "AUTH TLS" command is sent to the server to request an encrypted session. If the server does not recognize this
command, you receive a WebException exception.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.EndGetRequestStream FtpWebRequest.
EndGetRequestStream
I n this Article
Ends a pending asynchronous operation started with BeginGetRequestStream(AsyncCallback, Object).

public override System.IO.Stream EndGetRequestStream (IAsyncResult asyncResult);


override this.EndGetRequestStream : IAsyncResult -> System.IO.Stream

Parameters
asyncResult IAsyncResult IAsyncResult
The IAsyncResult object that was returned when the operation started.
Returns
Stream Stream
A writable Stream instance associated with this instance.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .
ArgumentException ArgumentException
asyncResult was not obtained by calling BeginGetRequestStream(AsyncCallback, Object).
InvalidOperationException InvalidOperationException
This method was already called for the operation identified by asyncResult .

Examples
The following code example demonstrates ending an asynchronous operation to get a request's stream. This code
example is part of a larger example provided for the FtpWebRequest class overview.
private static void EndGetStreamCallback(IAsyncResult ar)
{
FtpState state = (FtpState) ar.AsyncState;

Stream requestStream = null;


// End the asynchronous call to get the request stream.
try
{
requestStream = state.Request.EndGetRequestStream(ar);
// Copy the file contents to the request stream.
const int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
int count = 0;
int readBytes = 0;
FileStream stream = File.OpenRead(state.FileName);
do
{
readBytes = stream.Read(buffer, 0, bufferLength);
requestStream.Write(buffer, 0, readBytes);
count += readBytes;
}
while (readBytes != 0);
Console.WriteLine ("Writing {0} bytes to the stream.", count);
// IMPORTANT: Close the request stream before sending the request.
requestStream.Close();
// Asynchronously get the response to the upload request.
state.Request.BeginGetResponse(
new AsyncCallback (EndGetResponseCallback),
state
);
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine("Could not get the request stream.");
state.OperationException = e;
state.OperationComplete.Set();
return;
}

Remarks
If the operation has not completed, the EndGetRequestStream method blocks until the operation completes. To
determine whether the operation has completed, check the IsCompleted property before calling
EndGetRequestStream.
In addition to the exceptions noted in "Exceptions," EndGetRequestStream rethrows exceptions that were thrown while
opening the stream for writing.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.EndGetResponse FtpWebRequest.End
GetResponse
I n this Article
Ends a pending asynchronous operation started with BeginGetResponse(AsyncCallback, Object).

public override System.Net.WebResponse EndGetResponse (IAsyncResult asyncResult);


override this.EndGetResponse : IAsyncResult -> System.Net.WebResponse

Parameters
asyncResult IAsyncResult IAsyncResult
The IAsyncResult that was returned when the operation started.
Returns
WebResponse WebResponse
A WebResponse reference that contains an FtpWebResponse instance. This object contains the FTP server's response
to the request.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .
ArgumentException ArgumentException
asyncResult was not obtained by calling BeginGetResponse(AsyncCallback, Object).
InvalidOperationException InvalidOperationException
This method was already called for the operation identified by asyncResult .
WebException WebException
An error occurred using an HTTP proxy.

Examples
The following code example demonstrates ending an asynchronous operation to get a response. This code example is
part of a larger example provided for the FtpWebRequest class overview.
// The EndGetResponseCallback method
// completes a call to BeginGetResponse.
private static void EndGetResponseCallback(IAsyncResult ar)
{
FtpState state = (FtpState) ar.AsyncState;
FtpWebResponse response = null;
try
{
response = (FtpWebResponse) state.Request.EndGetResponse(ar);
response.Close();
state.StatusDescription = response.StatusDescription;
// Signal the main application thread that
// the operation is complete.
state.OperationComplete.Set();
}
// Return exceptions to the main application thread.
catch (Exception e)
{
Console.WriteLine ("Error getting response.");
state.OperationException = e;
state.OperationComplete.Set();
}
}

Remarks
If the operation has not completed at the time the EndGetResponse method is called, EndGetResponse blocks until the
operation completes. To prevent blocking, check the IsCompleted property before calling EndGetResponse.
In addition to the exceptions noted in "Exceptions," EndGetResponse rethrows exceptions that were thrown while
communicating with the server.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See WebRequestWebRequest
Also WebResponseWebResponse
GetResponse()GetResponse()
FtpWebRequest.GetRequestStream FtpWebRequest.Get
RequestStream
I n this Article
Retrieves the stream used to upload data to an FTP server.

public override System.IO.Stream GetRequestStream ();


override this.GetRequestStream : unit -> System.IO.Stream

Returns
Stream Stream
A writable Stream instance used to store data to be sent to the server by the current request.
Exceptions
InvalidOperationException InvalidOperationException
BeginGetRequestStream(AsyncCallback, Object) has been called and has not completed.
-or-
An HTTP proxy is enabled, and you attempted to use an FTP command other than DownloadFile, ListDirectory, or
ListDirectoryDetails.
WebException WebException
A connection to the FTP server could not be established.
ProtocolViolationException ProtocolViolationException
The Method property is not set to UploadFile or AppendFile.

Examples
The following code example demonstrates copying a file to a request's data stream and sending a request to the server
to upload the data and append it to a file.
public static bool AppendFileOnServer(string fileName, Uri serverUri)
{
// The URI described by serverUri should use the ftp:// scheme.
// It contains the name of the file on the server.
// Example: ftp://contoso.com/someFile.txt.
// The fileName parameter identifies the file containing
// the data to be appended to the file on the server.

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.AppendFile;

StreamReader sourceStream = new StreamReader(fileName);


byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;

// This example assumes the FTP site uses anonymous logon.


request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse) request.GetResponse();

Console.WriteLine("Append status: {0}",response.StatusDescription);

response.Close();
return true;
}

Remarks
Set the request properties before calling the GetRequestStream method. After writing the data to the stream, you must
close the stream prior to sending the request.
If you have not set the Method property to UploadFile or AppendFile, you cannot get the stream.
GetRequestStream blocks while waiting for the stream. To prevent this, call the BeginGetRequestStream method in
place of GetRequestStream.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.GetResponse FtpWebRequest.Get
Response
I n this Article
Returns the FTP server response.

public override System.Net.WebResponse GetResponse ();


override this.GetResponse : unit -> System.Net.WebResponse

Returns
WebResponse WebResponse
A WebResponse reference that contains an FtpWebResponse instance. This object contains the FTP server's response
to the request.
Exceptions
InvalidOperationException InvalidOperationException
GetResponse() or BeginGetResponse(AsyncCallback, Object) has already been called for this instance.
-or-
An HTTP proxy is enabled, and you attempted to use an FTP command other than DownloadFile, ListDirectory, or
ListDirectoryDetails.
WebException WebException
EnableSsl is set to true , but the server does not support this feature.
-or-
A Timeout was specified and the timeout has expired.

Examples
The following code example demonstrates copying a file to a request's data stream and sending a request to append
data to a file to the server. The example calls GetResponse to send the request and block until the response is returned
by the server.
public static bool AppendFileOnServer(string fileName, Uri serverUri)
{
// The URI described by serverUri should use the ftp:// scheme.
// It contains the name of the file on the server.
// Example: ftp://contoso.com/someFile.txt.
// The fileName parameter identifies the file containing
// the data to be appended to the file on the server.

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.AppendFile;

StreamReader sourceStream = new StreamReader(fileName);


byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;

// This example assumes the FTP site uses anonymous logon.


request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse) request.GetResponse();

Console.WriteLine("Append status: {0}",response.StatusDescription);

response.Close();
return true;
}

Remarks
To access the FTP -specific properties, you must cast the WebResponse object returned by this method to
FtpWebResponse.
GetResponse causes a control connection to be established, and might also create a data connection. GetResponse
blocks until the response is received. To prevent this, you can perform this operation asynchronously by calling the
BeginGetResponse and EndGetResponse methods in place of GetResponse.
If the Proxy property is set, either directly or in a configuration file, communications with the FTP server are made
through the proxy.
If a WebException is thrown, use the Response and Status properties of the exception to determine the response from
the server.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
Note

Multiple calls to GetResponse return the same response object; the request is not reissued.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.Headers FtpWebRequest.Headers
I n this Article
Gets an empty WebHeaderCollection object.
public override System.Net.WebHeaderCollection Headers { get; set; }
member this.Headers : System.Net.WebHeaderCollection with get, set

Returns
WebHeaderCollection WebHeaderCollection
An empty WebHeaderCollection object.

Remarks
The Headers property is provided only for compatibility with other implementations of the WebRequest and
WebResponse classes. There is no reason to use Headers.
FtpWebRequest.KeepAlive FtpWebRequest.KeepAlive
I n this Article
Gets or sets a Boolean value that specifies whether the control connection to the FTP server is closed after the request
completes.

public bool KeepAlive { get; set; }


member this.KeepAlive : bool with get, set

Returns
Boolean Boolean
true if the connection to the server should not be destroyed; otherwise, false . The default value is true .
Exceptions
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example retrieves and displays property values for a specified FtpWebRequest object.
Console.WriteLine("Passive: {0} Keep alive: {1} Binary: {2} Timeout: {3}.",
request.UsePassive,
request.KeepAlive,
request.UseBinary,
request.Timeout == -1 ? "none" : request.Timeout.ToString()
);

Remarks
When the KeepAlive property is set to false , the control connection is closed when you call the Close method.
Changing KeepAlive after calling the GetRequestStream, BeginGetRequestStream, GetResponse, or BeginGetResponse
method causes an InvalidOperationException exception.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.Method FtpWebRequest.Method
I n this Article
Gets or sets the command to send to the FTP server.
public override string Method { get; set; }
member this.Method : string with get, set

Returns
String String
A String value that contains the FTP command to send to the server. The default value is DownloadFile.
Exceptions
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.
ArgumentException ArgumentException
The method is invalid.
-or-
The method is not supported.
-or-
Multiple methods were specified.

Examples
The following code example sets this property to DeleteFile.
public static bool DeleteFileOnServer(Uri serverUri)
{
// The serverUri parameter should use the ftp:// scheme.
// It contains the name of the server file that is to be deleted.
// Example: ftp://contoso.com/someFile.txt.
//

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();


Console.WriteLine("Delete status: {0}",response.StatusDescription);
response.Close();
return true;
}

Remarks
The Method property determines which command is sent to the server. You set the Method by using the strings
defined in the public field members of the WebRequestMethods.Ftp class. Note that the strings defined in the
WebRequestMethods.Ftp class are the only supported options for the Method property. Setting the Method property
to any other value will result in an ArgumentException exception.
When setting Method to UploadFile, you must do so before calling the GetRequestStream method. Failure to call these
members in the correct order causes a ProtocolViolationException exception when you attempt to get the request
stream.
The credentials supplied for the FtpWebRequest object must have permission to perform the specified method. If not,
the FTP command fails.
To determine the success or failure of a command, check the StatusCode and StatusDescription properties.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.PreAuthenticate FtpWebRequest.Pre
Authenticate
I n this Article
Always throws a NotSupportedException.

public override bool PreAuthenticate { get; set; }


member this.PreAuthenticate : bool with get, set

Returns
Boolean Boolean
Always throws a NotSupportedException.
Exceptions
NotSupportedException NotSupportedException
Preauthentication is not supported for FTP.

Remarks
The PreAuthenticate property is provided only for compatibility with other implementations of the WebRequest and
WebResponse classes.
FtpWebRequest.Proxy FtpWebRequest.Proxy
I n this Article
Gets or sets the proxy used to communicate with the FTP server.
public override System.Net.IWebProxy Proxy { get; set; }
member this.Proxy : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
An IWebProxy instance responsible for communicating with the FTP server. On .NET Core, its value is null .
Exceptions
ArgumentNullException ArgumentNullException
This property cannot be set to null .
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example displays this property value.
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
Console.WriteLine("Proxy: (none)");
}

Console.WriteLine("ConnectionGroup: {0}",
request.ConnectionGroupName == null ? "none" : request.ConnectionGroupName
);

Remarks
On .NE T Framework
The Proxy property identifies the IWebProxy instance that communicates with the FTP server. The proxy is set by the
system by using configuration files and the Internet Explorer Local Area Network settings. To specify that no proxy
should be used, set Proxy to the proxy instance returned by the GlobalProxySelection.GetEmptyWebProxy method. For
more information about automatic proxy detection, see Automatic Proxy Detection.
You must set Proxy before writing data to the request's stream or getting the response. Changing Proxy after calling
the GetRequestStream, BeginGetRequestStream, GetResponse, or BeginGetResponse method causes an
InvalidOperationException exception.
The FtpWebRequest class supports HTTP and ISA Firewall Client proxies.
If the specified proxy is an HTTP proxy, only the DownloadFile, ListDirectory, and ListDirectoryDetails commands are
supported.
On .NE T Core
The FtpWebRequest.Proxy property is not supported. Setting the property has no effect. Getting the property value
returns null .
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.ReadWriteTimeout FtpWebRequest.
ReadWriteTimeout
I n this Article
Gets or sets a time-out when reading from or writing to a stream.

public int ReadWriteTimeout { get; set; }


member this.ReadWriteTimeout : int with get, set

Returns
Int32 Int32
The number of milliseconds before the reading or writing times out. The default value is 300,000 milliseconds (5
minutes).
Exceptions
InvalidOperationException InvalidOperationException
The request has already been sent.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for a set operation is less than or equal to zero and is not equal to Infinite.

Remarks
The ReadWriteTimeout is used when writing to the stream returned by the GetRequestStream method or reading from
the stream returned by the GetResponseStream method.
Specifically, the ReadWriteTimeout property controls the time-out for the Read method, which is used to read the
stream returned by the GetResponseStream method, and for the Write method, which is used to write to the stream
returned by the GetRequestStream method. If the time-out period is exceeded, the calling method throws a
WebException with WebExceptionStatus set to Timeout.
To specify the amount of time to wait for the request to complete, use the Timeout property.
FtpWebRequest.RenameTo FtpWebRequest.RenameTo
I n this Article
Gets or sets the new name of a file being renamed.
public string RenameTo { get; set; }
member this.RenameTo : string with get, set

Returns
String String
The new name of the file being renamed.
Exceptions
ArgumentException ArgumentException
The value specified for a set operation is null or an empty string.
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.
FtpWebRequest.RequestUri FtpWebRequest.RequestUri
I n this Article
Gets the URI requested by this instance.
public override Uri RequestUri { get; }
member this.RequestUri : Uri

Returns
Uri Uri
A Uri instance that identifies a resource that is accessed using the File Transfer Protocol.

Examples
The following code example displays this property value.
Console.WriteLine("User {0} {1}",
request.Credentials.GetCredential(request.RequestUri,"basic").UserName,
request.RequestUri
);

Remarks
The value of the RequestUri property is the URI specified when the Create method was called to obtain this instance.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.ServicePoint FtpWebRequest.Service
Point
I n this Article
Gets the ServicePoint object used to connect to the FTP server.

public System.Net.ServicePoint ServicePoint { get; }


member this.ServicePoint : System.Net.ServicePoint

Returns
ServicePoint ServicePoint
A ServicePoint object that can be used to customize connection behavior.

Examples
The following code example retrieves the service point from a request and sets the maximum number of connections
to one.
public static bool ListFilesOnServer(Uri serverUri)
{
// The serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.ListDirectory;

// Get the ServicePoint object used for this request, and limit it to one connection.
// In a real-world application you might use the default number of connections (2),
// or select a value that works best for your application.

ServicePoint sp = request.ServicePoint;
Console.WriteLine("ServicePoint connections = {0}.", sp.ConnectionLimit);
sp.ConnectionLimit = 1;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();

// The following streams are used to read the data returned from the server.
Stream responseStream = null;
StreamReader readStream = null;
try
{
responseStream = response.GetResponseStream();
readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);

if (readStream != null)
{
// Display the data received from the server.
Console.WriteLine(readStream.ReadToEnd());
}
Console.WriteLine("List status: {0}",response.StatusDescription);
}
finally
{
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
}

return true;
}

Remarks
If no ServicePoint object exists, one is created for the FTP server. To set the maximum number of connections that can
be open for an FTP server, set the ConnectionLimit property of the ServicePoint instance returned by this property.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.Timeout FtpWebRequest.Timeout
I n this Article
Gets or sets the number of milliseconds to wait for a request.
public override int Timeout { get; set; }
member this.Timeout : int with get, set

Returns
Int32 Int32
An Int32 value that contains the number of milliseconds to wait before a request times out. The default value is Infinite.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified is less than zero and is not Infinite.
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example sets this property.
public static bool UploadUniqueFileOnServer (Uri serverUri, string fileName)
{
// The URI described by serverUri should use the ftp:// scheme.
// It contains the name of the directory on the server.
// Example: ftp://contoso.com.
//
// The fileName parameter identifies the file containing the data to be uploaded.

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.UploadFileWithUniqueName;
// Set a time limit for the operation to complete.
request.Timeout = 600000;

// Copy the file contents to the request stream.


const int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];
int count = 0;
int readBytes = 0;
FileStream stream = File.OpenRead(fileName);
Stream requestStream = request.GetRequestStream();
do
{
readBytes = stream.Read(buffer, 0, bufferLength);
requestStream.Write(buffer, 0, bufferLength);
count += readBytes;
}
while (readBytes != 0);

Console.WriteLine ("Writing {0} bytes to the stream.", count);


// IMPORTANT: Close the request stream before sending the request.
requestStream.Close();
FtpWebResponse response = (FtpWebResponse) request.GetResponse();
Console.WriteLine("Upload status: {0}, {1}",response.StatusCode, response.StatusDescription);
Console.WriteLine ("File name: {0}", response.ResponseUri);
response.Close();
return true;
}

Remarks
To specify an infinite value, set the Timeout property to Infinite (-1). This is the default value.
Timeout is the number of milliseconds that a synchronous request made with the GetResponse method waits for a
response and that the GetRequestStream method waits for a stream. If a resource does not respond within the time-
out period, the request throws a WebException with the Status property set to Timeout.
Changing Timeout after calling the GetRequestStream, BeginGetRequestStream, GetResponse, or BeginGetResponse
method causes an InvalidOperationException exception.
A Domain Name System (DNS ) query may take up to 15 seconds to return or time out. If your request contains a host
name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more
before a WebException is thrown to indicate a time-out on your request.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.UseBinary FtpWebRequest.UseBinary
I n this Article
Gets or sets a Boolean value that specifies the data type for file transfers.
public bool UseBinary { get; set; }
member this.UseBinary : bool with get, set

Returns
Boolean Boolean
true to indicate to the server that the data to be transferred is binary; false to indicate that the data is text. The
default value is true .

Exceptions
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example retrieves and displays property values for a specified FtpWebRequest object.
Console.WriteLine("Passive: {0} Keep alive: {1} Binary: {2} Timeout: {3}.",
request.UsePassive,
request.KeepAlive,
request.UseBinary,
request.Timeout == -1 ? "none" : request.Timeout.ToString()
);

Remarks
If you are sending binary data, such as an image, set this property to true . If you are sending text, set the property to
false . Specifying true causes the FtpWebRequest to send a "TYPE I" command to the server. Specifying false
causes the FtpWebRequest to send a "Type A" command to the server. FTP servers can ignore these commands.
Changing UseBinary after calling the GetRequestStream, BeginGetRequestStream, GetResponse, or
BeginGetResponse method causes an InvalidOperationException exception.
See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebRequest.UseDefaultCredentials FtpWebRequest.
UseDefaultCredentials
I n this Article
Always throws a NotSupportedException.

public override bool UseDefaultCredentials { get; set; }


member this.UseDefaultCredentials : bool with get, set

Returns
Boolean Boolean
Always throws a NotSupportedException.
Exceptions
NotSupportedException NotSupportedException
Default credentials are not supported for FTP.

Remarks
The UseDefaultCredentials property is provided only for compatibility with other implementations of the WebRequest
and WebResponse classes. There is no reason to use UseDefaultCredentials.
FtpWebRequest.UsePassive FtpWebRequest.UsePassive
I n this Article
Gets or sets the behavior of a client application's data transfer process.
public bool UsePassive { get; set; }
member this.UsePassive : bool with get, set

Returns
Boolean Boolean
false if the client application's data transfer process listens for a connection on the data port; otherwise, true if the
client should initiate a connection on the data port. The default value is true .

Exceptions
InvalidOperationException InvalidOperationException
A new value was specified for this property for a request that is already in progress.

Examples
The following code example retrieves and displays property values for a specified FtpWebRequest object.
// DisplayRequestProperties prints a request's properties.
// This method should be called after the request is sent to the server.

private static void DisplayRequestProperties(FtpWebRequest request)


{
Console.WriteLine("User {0} {1}",
request.Credentials.GetCredential(request.RequestUri,"basic").UserName,
request.RequestUri
);
Console.WriteLine("Request: {0} {1}",
request.Method,
request.RequestUri
);
Console.WriteLine("Passive: {0} Keep alive: {1} Binary: {2} Timeout: {3}.",
request.UsePassive,
request.KeepAlive,
request.UseBinary,
request.Timeout == -1 ? "none" : request.Timeout.ToString()
);
IWebProxy proxy = request.Proxy;
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(request.RequestUri));
}
else
{
Console.WriteLine("Proxy: (none)");
}

Console.WriteLine("ConnectionGroup: {0}",
request.ConnectionGroupName == null ? "none" : request.ConnectionGroupName
);

Console.WriteLine("Encrypted connection: {0}",


request.EnableSsl);

Console.WriteLine("Method: {0}", request.Method);


}

Remarks
Setting the UsePassive property to true sends the " PASV" command to the server. This command requests the server
to listen on a data port and to wait for a connection rather than initiate one upon receipt of a transfer command.
For a description of the behaviors that are specified using UsePassive, see RFC 959: "File Transfer Protocol", Section
3.2: "Establishing Data Connections" and Section 4.1.2: "Transfer Parameter Commands".
Changing UsePassive after calling the GetRequestStream, BeginGetRequestStream, GetResponse, or
BeginGetResponse method causes an InvalidOperationException exception.
If UsePassive is set to true , the FTP server may not send the size of the file, and download progress can always be
zero. If UsePassive is set to false , a firewall can raise an alert and block the file download.

See WebRequestWebRequest
Also WebResponseWebResponse
FtpWebResponse FtpWebResponse Class
Encapsulates a File Transfer Protocol (FTP ) server's response to a request.

D eclaration
public class FtpWebResponse : System.Net.WebResponse
type FtpWebResponse = class
inherit WebResponse

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
WebResponse WebResponse

Remarks
Instances of FtpWebResponse are obtained by calling the GetResponse method. The returned object must be cast to an
FtpWebResponse. When your application no longer needs the FtpWebResponse object, call the Close method to free
the resources held by the FtpWebResponse.
The StatusCode property contains the status code returned by the server, and the StatusDescription property returns
the status code and a message that describes the status. The values returned by these properties change as the
messages are returned by the server.
Any data returned by the request, such as the list of file names returned for a ListDirectory request, is available in the
stream returned by the GetResponseStream method. The length of the stream data can be obtained from the
ContentLength property.

Properties
BannerMessage
BannerMessage

Gets the message sent by the FTP server when a connection is established prior to logon.

ContentLength
ContentLength

Gets the length of the data received from the FTP server.

ContentType
ContentType

ExitMessage
ExitMessage

Gets the message sent by the server when the FTP session is ending.
Headers
Headers

Gets an empty WebHeaderCollection object.

LastModified
LastModified

Gets the date and time that a file on an FTP server was last modified.

ResponseUri
ResponseUri

Gets the URI that sent the response to the request.

StatusCode
StatusCode

Gets the most recent status code sent from the FTP server.

StatusDescription
StatusDescription

Gets text that describes a status code sent from the FTP server.

SupportsHeaders
SupportsHeaders

Gets a value that indicates whether the Headers property is supported by the FtpWebResponse instance.

WelcomeMessage
WelcomeMessage

Gets the message sent by the FTP server when authentication is complete.

Methods
Close()
Close()

Frees the resources held by the response.

GetResponseStream()
GetResponseStream()

Retrieves the stream that contains response data sent from an FTP server.
See Also
FtpStatusCode FtpStatusCode
WebResponse WebResponse
FtpWebResponse.BannerMessage FtpWebResponse.
BannerMessage
I n this Article
Gets the message sent by the FTP server when a connection is established prior to logon.

public string BannerMessage { get; }


member this.BannerMessage : string

Returns
String String
A String that contains the banner message sent by the server; otherwise, Empty if no message is sent.

Examples
The following code example displays the value of this property.
Console.WriteLine("Banner message: {0}",
response.BannerMessage);

See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.Close FtpWebResponse.Close
I n this Article
Frees the resources held by the response.
public override void Close ();
override this.Close : unit -> unit

Examples
The following code example downloads data from a server, reads the data from the response stream, and then closes it.
public static bool DownloadFileFromServer(Uri serverUri, string localFileName)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
// Note that the cast to FtpWebRequest is done only
// for the purposes of illustration. If your application
// does not set any properties other than those defined in the
// System.Net.WebRequest class, you can use the following line instead:
// WebRequest request = WebRequest.Create(serverUri);
//
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();

Stream responseStream = null;


StreamReader readStream = null;
StreamWriter writeStream = null;
try
{
responseStream = response.GetResponseStream();
readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
// Display information about the data received from the server.
Console.WriteLine("Bytes received: {0}",response.ContentLength);

Console.WriteLine("Message from server: {0}", response.StatusDescription);


Console.WriteLine("Resource: {0}", response.ResponseUri);

// Write the bytes received from the server to the local file.
if (readStream != null)
{
writeStream = new StreamWriter(localFileName, false);
writeStream.Write(readStream.ReadToEnd());
}
}
finally
{
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
if (writeStream != null)
{
writeStream.Close();
}
}
return true;
}

Remarks
The Close method closes the data stream returned by the GetResponseStream method if the KeepAlive property is
false . During the close, data might be sent to the server on the control connection.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.ContentLength FtpWebResponse.
ContentLength
I n this Article
Gets the length of the data received from the FTP server.

public override long ContentLength { get; }


member this.ContentLength : int64

Returns
Int64 Int64
An Int64 value that contains the number of bytes of data received from the FTP server.

Examples
The following code example downloads a file from on the specified FTP server. This property contains the number of
bytes in the downloaded file.
public static bool DownloadFileFromServer(Uri serverUri, string localFileName)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
// Note that the cast to FtpWebRequest is done only
// for the purposes of illustration. If your application
// does not set any properties other than those defined in the
// System.Net.WebRequest class, you can use the following line instead:
// WebRequest request = WebRequest.Create(serverUri);
//
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();

Stream responseStream = null;


StreamReader readStream = null;
StreamWriter writeStream = null;
try
{
responseStream = response.GetResponseStream();
readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
// Display information about the data received from the server.
Console.WriteLine("Bytes received: {0}",response.ContentLength);

Console.WriteLine("Message from server: {0}", response.StatusDescription);


Console.WriteLine("Resource: {0}", response.ResponseUri);

// Write the bytes received from the server to the local file.
if (readStream != null)
{
writeStream = new StreamWriter(localFileName, false);
writeStream.Write(readStream.ReadToEnd());
}
}
finally
{
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
if (writeStream != null)
{
writeStream.Close();
}
}
return true;
}

Remarks
When a response stream is returned by the FTP server, the ContentLength property contains the number of bytes in
the stream. ContentLength returns −1 if no data was returned in the response or if the server did not send content
length information. The return value is greater than or equal to zero if data was or should have been returned. For
example, for requests that use the ListDirectory field, the ContentLength property always returns −1. For requests that
use the UploadFile method, the ContentLength property is always zero. For requests that use the DownloadFile
method, the property is greater than zero if the downloaded file contained data and is zero if it was empty.
For requests that use the GetFileSize method, ContentLength returns the size of the specified file on the server.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.ContentType FtpWebResponse.Content
Type
I n this Article
public override string ContentType { get; }
member this.ContentType : string

Returns
String String
FtpWebResponse.ExitMessage FtpWebResponse.Exit
Message
I n this Article
Gets the message sent by the server when the FTP session is ending.

public string ExitMessage { get; }


member this.ExitMessage : string

Returns
String String
A String that contains the exit message sent by the server; otherwise, Empty if no message is sent.

Examples
The following code example displays the value of this property.
Console.WriteLine("Exit message: {0}",
response.ExitMessage);

Remarks
The ExitMessage property is not available until the connection to the server is closed or reused. If the KeepAlive
property is true , the connection used by this request is not closed, which prevents the server from sending an exit
message.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
WelcomeMessageWelcomeMessage
BannerMessageBannerMessage
FtpWebResponse.GetResponseStream FtpWebResponse.
GetResponseStream
I n this Article
Retrieves the stream that contains response data sent from an FTP server.

public override System.IO.Stream GetResponseStream ();


override this.GetResponseStream : unit -> System.IO.Stream

Returns
Stream Stream
A readable Stream instance that contains data returned with the response; otherwise, Null if no response data was
returned by the server.
Exceptions
InvalidOperationException InvalidOperationException
The response did not return a data stream.

Examples
The following code example demonstrates getting the response stream for a ListDirectory request.
public static bool ListFilesOnServer(Uri serverUri)
{
// The serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.ListDirectory;

// Get the ServicePoint object used for this request, and limit it to one connection.
// In a real-world application you might use the default number of connections (2),
// or select a value that works best for your application.

ServicePoint sp = request.ServicePoint;
Console.WriteLine("ServicePoint connections = {0}.", sp.ConnectionLimit);
sp.ConnectionLimit = 1;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();

// The following streams are used to read the data returned from the server.
Stream responseStream = null;
StreamReader readStream = null;
try
{
responseStream = response.GetResponseStream();
readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);

if (readStream != null)
{
// Display the data received from the server.
Console.WriteLine(readStream.ReadToEnd());
}
Console.WriteLine("List status: {0}",response.StatusDescription);
}
finally
{
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
}

return true;
}

Remarks
After reading the data, you must close the stream. The stream is automatically closed when you close the
FtpWebResponse object that contains it.
An exception is thrown unless the request method is DownloadFile or ListDirectory.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
Close()Close()
FtpWebResponse.Headers FtpWebResponse.Headers
I n this Article
Gets an empty WebHeaderCollection object.
public override System.Net.WebHeaderCollection Headers { get; }
member this.Headers : System.Net.WebHeaderCollection

Returns
WebHeaderCollection WebHeaderCollection
An empty WebHeaderCollection object.

Remarks
The Headers property is provided only for compatibility with other implementations of the WebRequest and
WebResponse classes.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.LastModified FtpWebResponse.Last
Modified
I n this Article
Gets the date and time that a file on an FTP server was last modified.

public DateTime LastModified { get; }


member this.LastModified : DateTime

Returns
DateTime DateTime
A DateTime that contains the last modified date and time for a file.

Examples
The following code example displays the date and time that a file on an FTP server was last modified.
public static bool GetDateTimestampOnServer (Uri serverUri)
{
// The serverUri should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}

// Get the object used to communicate with the server.


FtpWebRequest request = (FtpWebRequest)WebRequest.Create (serverUri);
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
FtpWebResponse response = (FtpWebResponse)request.GetResponse ();
Console.WriteLine ("{0} {1}",serverUri,response.LastModified);

// The output from this method will vary depending on the


// file specified and your regional settings. It is similar to:
// ftp://contoso.com/Data.txt 4/15/2003 10:46:02 AM
return true;
}

Remarks
The LastModified property returns the data requested by the GetDateTimestamp method. For requests sent using any
other method, LastModified returns MinValue.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.ResponseUri FtpWebResponse.
ResponseUri
I n this Article
Gets the URI that sent the response to the request.

public override Uri ResponseUri { get; }


member this.ResponseUri : Uri

Returns
Uri Uri
A Uri instance that identifies the resource associated with this response.

Examples
The following code example displays the value of this property.
public static bool DownloadFileFromServer(Uri serverUri, string localFileName)
{
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
// Note that the cast to FtpWebRequest is done only
// for the purposes of illustration. If your application
// does not set any properties other than those defined in the
// System.Net.WebRequest class, you can use the following line instead:
// WebRequest request = WebRequest.Create(serverUri);
//
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DownloadFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();

Stream responseStream = null;


StreamReader readStream = null;
StreamWriter writeStream = null;
try
{
responseStream = response.GetResponseStream();
readStream = new StreamReader(responseStream, System.Text.Encoding.UTF8);
// Display information about the data received from the server.
Console.WriteLine("Bytes received: {0}",response.ContentLength);

Console.WriteLine("Message from server: {0}", response.StatusDescription);


Console.WriteLine("Resource: {0}", response.ResponseUri);

// Write the bytes received from the server to the local file.
if (readStream != null)
{
writeStream = new StreamWriter(localFileName, false);
writeStream.Write(readStream.ReadToEnd());
}
}
finally
{
if (readStream != null)
{
readStream.Close();
}
if (response != null)
{
response.Close();
}
if (writeStream != null)
{
writeStream.Close();
}
}
return true;
}

Remarks
Because of server- and resource-specific behaviors, such as redirection, the value returned by the RequestUri property
is not always the same as the value returned by the ResponseUri property.
For requests that use the UploadFileWithUniqueName method, ResponseUri returns the name of the file on the server.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.StatusCode FtpWebResponse.Status
Code
I n this Article
Gets the most recent status code sent from the FTP server.

public System.Net.FtpStatusCode StatusCode { get; }


member this.StatusCode : System.Net.FtpStatusCode

Returns
FtpStatusCode FtpStatusCode
An FtpStatusCode value that indicates the most recent status code returned with this response.

Examples
The following code example uploads a file to a server and displays the status.
public static bool UploadFileToServer(string fileName, Uri serverUri)
{
// The URI described by serverUri should use the ftp:// scheme.
// It contains the name of the file on the server.
// Example: ftp://contoso.com/someFile.txt.
//
// The fileName parameter identifies the file containing the data to be uploaded.

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.UploadFile;
// Don't set a time limit for the operation to complete.
request.Timeout = System.Threading.Timeout.Infinite;

// Copy the file contents to the request stream.


const int bufferLength = 2048;
byte[] buffer = new byte[bufferLength];

int count = 0;
int readBytes = 0;
FileStream stream = File.OpenRead(fileName);
Stream requestStream = request.GetRequestStream();
do
{
readBytes = stream.Read(buffer, 0, bufferLength);
requestStream.Write(buffer, 0, bufferLength);
count += readBytes;
}
while (readBytes != 0);

Console.WriteLine ("Writing {0} bytes to the stream.", count);


// IMPORTANT: Close the request stream before sending the request.
requestStream.Close();

FtpWebResponse response = (FtpWebResponse) request.GetResponse();


Console.WriteLine("Upload status: {0}, {1}", response.StatusCode, response.StatusDescription);

response.Close();
return true;
}

Remarks
The value returned by the StatusCode property is included in the StatusDescription property. When you are
downloading data, the value of StatusCode changes as status codes are returned by the FTP server. After you call the
GetResponse method, StatusCode contains an intermediate status code. When you call the Close method, StatusCode
contains the final status.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.StatusDescription FtpWebResponse.
StatusDescription
I n this Article
Gets text that describes a status code sent from the FTP server.

public string StatusDescription { get; }


member this.StatusDescription : string

Returns
String String
A String instance that contains the status code and message returned with this response.

Examples
The following code example sends a request to delete a file on an FTP server and displays the status message from the
server's response to the request.
public static bool DeleteFileOnServer(Uri serverUri)
{
// The serverUri parameter should use the ftp:// scheme.
// It contains the name of the server file that is to be deleted.
// Example: ftp://contoso.com/someFile.txt.
//

if (serverUri.Scheme != Uri.UriSchemeFtp)
{
return false;
}
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.Method = WebRequestMethods.Ftp.DeleteFile;

FtpWebResponse response = (FtpWebResponse) request.GetResponse();


Console.WriteLine("Delete status: {0}",response.StatusDescription);
response.Close();
return true;
}

Remarks
The text returned by the StatusDescription property includes the 3-digit StatusCode property value. When
downloading data, the value of StatusDescription changes as status codes are returned by the FTP server. After you call
the GetResponse method, StatusDescription contains an intermediate status code. When you call the Close method,
StatusDescription contains the final status.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
FtpWebResponse.SupportsHeaders FtpWebResponse.
SupportsHeaders
I n this Article
Gets a value that indicates whether the Headers property is supported by the FtpWebResponse instance.

public override bool SupportsHeaders { get; }


member this.SupportsHeaders : bool

Returns
Boolean Boolean
Returns Boolean.
true if the Headers property is supported by the FtpWebResponse instance; otherwise, false .

Remarks
This property is always true for .NET Framework 4.5.
FtpWebResponse.WelcomeMessage FtpWebResponse.
WelcomeMessage
I n this Article
Gets the message sent by the FTP server when authentication is complete.

public string WelcomeMessage { get; }


member this.WelcomeMessage : string

Returns
String String
A String that contains the welcome message sent by the server; otherwise, Empty if no message is sent.

Examples
The following code example displays the value of this property.
Console.WriteLine("Welcome message: {0}",
response.WelcomeMessage);

Remarks
If the connection is being reused (the KeepAlive property is set to true ), the WelcomeMessage property returns the
first welcome message received with the connection.
See FtpStatusCodeFtpStatusCode
Also WebResponseWebResponse
ExitMessageExitMessage
BannerMessageBannerMessage
GlobalProxySelection GlobalProxySelection Class
Contains a global default proxy instance for all HTTP requests.

D eclaration
[System.Obsolete("This class has been deprecated. Please use WebRequest.DefaultWebProxy instead
to access and set the global default proxy. Use 'null' instead of GetEmptyWebProxy.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("This class has been deprecated. Please use WebRequest.DefaultWebProxy instead
to access and set the global default proxy. Use 'null' instead of GetEmptyWebProxy.
https://go.microsoft.com/fwlink/?linkid=14202")]
public class GlobalProxySelection
type GlobalProxySelection = class

I nheritance H ierarchy
Object Object

Remarks
The GlobalProxySelection stores the proxy settings for the default proxy that WebRequest instances use to contact
Internet sites beyond the local network. The default proxy setting is initialized from the global or application
configuration file, and can be overridden for individual requests or disabled by setting the HttpWebRequest.Proxy
property to the result of the GetEmptyWebProxy method.
The proxy settings stored in GlobalProxySelection are used by any WebRequest derived objects that support proxies
and have their Proxy property value set to null (the default). Proxies are currently supported by FtpWebRequest,
HttpWebRequest, and WebClient.
Note Changes to the GlobalProxySelection after a request is made are not reflected in a WebRequest.

Constructors
GlobalProxySelection()
GlobalProxySelection()

Initializes a new instance of the GlobalProxySelection class.

Properties
Select
Select

Gets or sets the global HTTP proxy.

Methods
GetEmptyWebProxy()
GetEmptyWebProxy()

Returns an empty proxy instance.


See Also
GlobalProxySelection.GetEmptyWebProxy GlobalProxy
Selection.GetEmptyWebProxy
I n this Article
Returns an empty proxy instance.

public static System.Net.IWebProxy GetEmptyWebProxy ();


static member GetEmptyWebProxy : unit -> System.Net.IWebProxy

Returns
IWebProxy IWebProxy
An IWebProxy that contains no information.

Examples
The following code example creates a WebRequest instance that does not use a proxy.
using System;
using System.Net;
using System.IO;
namespace Examples.Http
{
public class TestGlobalProxySelection
{
public static void Main()
{
// Create a request for the Web page at www.contoso.com.
WebRequest request = WebRequest.Create("http://www.contoso.com");
// This application doesn't want the proxy to be used so it sets
// the global proxy to an empty proxy.
IWebProxy myProxy = GlobalProxySelection.GetEmptyWebProxy();
GlobalProxySelection.Select = myProxy;
// Get the response.
WebResponse response = request.GetResponse();
// Display the response to the console.
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
// Clean up.
reader.Close();
stream.Close();
response.Close();
}
}
}

Remarks
The GetEmptyWebProxy method returns a blank IWebProxy instance to indicate that no proxy is used to access an
Internet resource.
Instead of calling the GetEmptyWebProxy method, you can assign null to members such as the WebClient.Proxy
property, which specifies the proxy that communicates with remote servers on behalf of the WebClient object.
GlobalProxySelection
I n this Article
Initializes a new instance of the GlobalProxySelection class.
public GlobalProxySelection ();
GlobalProxySelection.Select GlobalProxySelection.Select
I n this Article
Gets or sets the global HTTP proxy.
public static System.Net.IWebProxy Select { get; set; }
member this.Select : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
An IWebProxy that every call to GetResponse() uses.
Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation was null .
SecurityException SecurityException
The caller does not have permission for the requested operation.

Examples
The following code example sets the Select property to the empty proxy.
using System;
using System.Net;
using System.IO;
namespace Examples.Http
{
public class TestGlobalProxySelection
{
public static void Main()
{
// Create a request for the Web page at www.contoso.com.
WebRequest request = WebRequest.Create("http://www.contoso.com");
// This application doesn't want the proxy to be used so it sets
// the global proxy to an empty proxy.
IWebProxy myProxy = GlobalProxySelection.GetEmptyWebProxy();
GlobalProxySelection.Select = myProxy;
// Get the response.
WebResponse response = request.GetResponse();
// Display the response to the console.
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
Console.WriteLine(reader.ReadToEnd());
// Clean up.
reader.Close();
stream.Close();
response.Close();
}
}
}

Remarks
The Select property sets the proxy that all WebRequest instances use if the request supports proxies and no proxy is
set explicitly using the Proxy property. Proxies are currently supported by FtpWebRequest and HttpWebRequest.
HttpContinueDelegate HttpContinueDelegate Delegate
Represents the method that notifies callers when a continue response is received by the client.

D eclaration
public delegate void HttpContinueDelegate(int StatusCode, WebHeaderCollection httpHeaders);
type HttpContinueDelegate = delegate of int * WebHeaderCollection -> unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
Use HttpContinueDelegate to specify the callback method to be called when an HTTP 100-continue response is
received from the server. When set, the delegate is called whenever the first protocol response of type
HttpStatusCode.Continue is received. This is a change from the behavior of the version 1.1 Framework.
Your event handler must declare the same parameters as the HttpContinueDelegate.
Note

StatusCode is always HttpStatusCode.Continue.


This is useful when the client wants to display the status of data being received from the server.
HttpListener HttpListener Class
Provides a simple, programmatically controlled HTTP protocol listener. This class cannot be inherited.

D eclaration
public sealed class HttpListener : IDisposable
type HttpListener = class
interface IDisposable

I nheritance H ierarchy
Object Object

Remarks
Using the HttpListener class, you can create a simple HTTP protocol listener that responds to HTTP requests. The
listener is active for the lifetime of the HttpListener object and runs within your application with its permissions.
To use HttpListener, create a new instance of the class using the HttpListener constructor and use the Prefixes property
to gain access to the collection that holds the strings that specify which Uniform Resource Identifier (URI) prefixes the
HttpListener should process.
A URI prefix string is composed of a scheme (http or https), a host, an optional port, and an optional path. An example
of a complete prefix string is http://www.contoso.com:8080/customerData/. Prefixes must end in a forward slash ("/").
The HttpListener object with the prefix that most closely matches a requested URI responds to the request. Multiple
HttpListener objects cannot add the same prefix; a Win32Exception exception is thrown if a HttpListener adds a prefix
that is already in use.
When a port is specified, the host element can be replaced with "*" to indicate that the HttpListener accepts requests
sent to the port if the requested URI does not match any other prefix. For example, to receive all requests sent to port
8080 when the requested URI is not handled by any HttpListener, the prefix is http://*:8080/. Similarly, to specify that
the HttpListener accepts all requests sent to a port, replace the host element with the "+" character. For example,
https://+:8080. The "*" and "+" characters can be present in prefixes that include paths.
Starting with .NET Core 2.0 or .NET Framework 4.6 on Windows 10, wildcard subdomains are supported in URI
prefixes that are managed by an HttpListener object. To specify a wildcard subdomain, use the "*" character as part of
the hostname in a URI prefix. For example, http://*.foo.com/. Pass this as the argument to the Add method. This works
as of .NET Core 2.0 or .NET Framework 4.6 on Windows 10; in earlier versions, this generates an
HttpListenerException.
W arning

Top-level wildcard bindings (http://*:8080/ and http://+:8080) should not be used. Top-level wildcard bindings can
open up your app to security vulnerabilities. This applies to both strong and weak wildcards. Use explicit host names
rather than wildcards. Subdomain wildcard binding (for example, *.mysub.com ) doesn't have this security risk if you
control the entire parent domain (as opposed to *.com , which is vulnerable). See rfc7230 section-5.4 for more
information.
To begin listening for requests from clients, add the URI prefixes to the collection and call the Start method.
HttpListener offers both synchronous and asynchronous models for processing client requests. Requests and their
associated responses are accessed using the HttpListenerContext object returned by the GetContext method or its
asynchronous counterparts, the BeginGetContext and EndGetContext methods.
The synchronous model is appropriate if your application should block while waiting for a client request and if you
want to process only one request at a time. Using the synchronous model, call the GetContext method, which waits for
a client to send a request. The method returns an HttpListenerContext object to you for processing when one occurs.
In the more complex asynchronous model, your application does not block while waiting for requests and each request
is processed in its own execution thread. Use the BeginGetContext method to specify an application-defined method to
be called for each incoming request. Within that method, call the EndGetContext method to obtain the request, process
it, and respond.
In either model, incoming requests are accessed using the HttpListenerContext.Request property and are represented
by HttpListenerRequest objects. Similarly, responses are accessed using the HttpListenerContext.Response property
and are represented by HttpListenerResponse objects. These objects share some functionality with the
HttpWebRequest and HttpWebResponse objects, but the latter objects cannot be used in conjunction with HttpListener
because they implement client, not server, behaviors.
An HttpListener can require client authentication. You can either specify a particular scheme to use for authentication,
or you can specify a delegate that determines the scheme to use. You must require some form of authentication to
obtain information about the client's identity. For additional information, see the User, AuthenticationSchemes, and
AuthenticationSchemeSelectorDelegate properties.
Note

If you create an HttpListener using https, you must select a Server Certificate for that listener. Otherwise, an
HttpWebRequest query of this HttpListener will fail with an unexpected close of the connection.
Note

You can configure Server Certificates and other listener options by using Network Shell (netsh.exe). See Network Shell
(Netsh) for more details. The executable began shipping with Windows Server 2008 and Windows Vista.
Note

If you specify multiple authentication schemes for the HttpListener, the listener will challenge clients in the following
order: Negotiate , NTLM , Digest , and then Basic .

Constructors
HttpListener()
HttpListener()

Initializes a new instance of the HttpListener class.

Properties
AuthenticationSchemes
AuthenticationSchemes

Gets or sets the scheme used to authenticate clients.

AuthenticationSchemeSelectorDelegate
AuthenticationSchemeSelectorDelegate

Gets or sets the delegate called to determine the protocol used to authenticate clients.

DefaultServiceNames
DefaultServiceNames

Gets a default list of Service Provider Names (SPNs) as determined by registered prefixes.

ExtendedProtectionPolicy
ExtendedProtectionPolicy

Gets or sets the ExtendedProtectionPolicy to use for extended protection for a session.

ExtendedProtectionSelectorDelegate
ExtendedProtectionSelectorDelegate

Gets or sets the delegate called to determine the ExtendedProtectionPolicy to use for each request.

IgnoreWriteExceptions
IgnoreWriteExceptions

Gets or sets a Boolean value that specifies whether your application receives exceptions that occur when an
HttpListener sends the response to the client.

IsListening
IsListening

Gets a value that indicates whether HttpListener has been started.

IsSupported
IsSupported

Gets a value that indicates whether HttpListener can be used with the current operating system.

Prefixes
Prefixes

Gets the Uniform Resource Identifier (URI) prefixes handled by this HttpListener object.

Realm
Realm

Gets or sets the realm, or resource partition, associated with this HttpListener object.

TimeoutManager
TimeoutManager

The timeout manager for this HttpListener instance.


UnsafeConnectionNtlmAuthentication
UnsafeConnectionNtlmAuthentication

Gets or sets a Boolean value that controls whether, when NTLM is used, additional requests using the same
Transmission Control Protocol (TCP ) connection are required to authenticate.

Methods
Abort()
Abort()

Shuts down the HttpListener object immediately, discarding all currently queued requests.

BeginGetContext(AsyncCallback, Object)
BeginGetContext(AsyncCallback, Object)

Begins asynchronously retrieving an incoming request.

Close()
Close()

Shuts down the HttpListener.

EndGetContext(IAsyncResult)
EndGetContext(IAsyncResult)

Completes an asynchronous operation to retrieve an incoming client request.

GetContext()
GetContext()

Waits for an incoming request and returns when one is received.

GetContextAsync()
GetContextAsync()

Waits for an incoming request as an asynchronous operation.

Start()
Start()

Allows this instance to receive incoming requests.

Stop()
Stop()
Causes this instance to stop receiving incoming requests.

IDisposable.Dispose()
IDisposable.Dispose()

Releases the resources held by this HttpListener object.

See Also
HttpListener.Abort HttpListener.Abort
I n this Article
Shuts down the HttpListener object immediately, discarding all currently queued requests.
public void Abort ();
member this.Abort : unit -> unit

Examples
The following code example demonstrates calling this method.

public static void CheckTestUrl(HttpListener listener, HttpListenerRequest request)


{
if (request.RawUrl == "/www.contoso.com/test/NoReply")
{
listener.Abort ();
return;
}

Remarks
This method disposes of all resources held by this listener. Any pending requests are unable to complete.
After calling this method, you will receive an ObjectDisposedException if you attempt to use this HttpListener.
HttpListener.AuthenticationSchemes HttpListener.
AuthenticationSchemes
I n this Article
Gets or sets the scheme used to authenticate clients.

public System.Net.AuthenticationSchemes AuthenticationSchemes { get; set; }


member this.AuthenticationSchemes : System.Net.AuthenticationSchemes with get, set

Returns
AuthenticationSchemes AuthenticationSchemes
A bitwise combination of AuthenticationSchemes enumeration values that indicates how clients are to be
authenticated. The default value is Anonymous.
Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example demonstrates using the AuthenticationSchemes property to specify an authentication
scheme.
public static void SimpleListenerWithUnsafeAuthentication(string[] prefixes)
{
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
// Specify Negotiate as the authentication scheme.
listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
// If NTLM is used, we will allow multiple requests on the same
// connection to use the authentication information of first request.
// This improves performance but does reduce the security of your
// application.
listener.UnsafeConnectionNtlmAuthentication = true;
// This listener does not want to receive exceptions
// that occur when sending the response to the client.
listener.IgnoreWriteExceptions = true;
Console.WriteLine("Listening...");
// ... process requests here.

listener.Close();
}

Remarks
The HttpListener uses the specified scheme to authenticate all incoming requests. The GetContext and EndGetContext
methods return an incoming client request only if the HttpListener successfully authenticates the request.
You can interrogate the identity of a successfully authenticated client by using the HttpListenerContext.User property.
If you want an HttpListener object to use different authentication mechanisms based on characteristics of the requests
it receives (for example, the request's Url or UserHostName property), you must implement a method that chooses the
authentication scheme. For instructions about how to do this, see the AuthenticationSchemeSelectorDelegate property
documentation.
Note

To set this property to enable Digest, NTLM, or Negotiate requires the SecurityPermission, ControlPrincipal.
HttpListener.AuthenticationSchemeSelectorDelegate
HttpListener.AuthenticationSchemeSelectorDelegate
I n this Article
Gets or sets the delegate called to determine the protocol used to authenticate clients.

public System.Net.AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate { get; set; }


member this.AuthenticationSchemeSelectorDelegate : System.Net.AuthenticationSchemeSelector with get,
set

Returns
AuthenticationSchemeSelector AuthenticationSchemeSelector
An AuthenticationSchemeSelector delegate that invokes the method used to select an authentication protocol. The
default value is null .
Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example sets the value of this property.
// Set up a listener.
HttpListener listener = new HttpListener();
HttpListenerPrefixCollection prefixes = listener.Prefixes;
prefixes.Add(@"http://localhost:8080/");
prefixes.Add(@"http://contoso.com:8080/");

// Specify the authentication delegate.


listener.AuthenticationSchemeSelectorDelegate =
new AuthenticationSchemeSelector (AuthenticationSchemeForClient);

// Start listening for requests and process them


// synchronously.
listener.Start();

The following code example provides an implementation of a method invoked by an AuthenticationSchemeSelector


delegate.
static AuthenticationSchemes AuthenticationSchemeForClient(HttpListenerRequest request)
{
Console.WriteLine("Client authentication protocol selection in progress...");
// Do not authenticate local machine requests.
if (request.RemoteEndPoint.Address.Equals (IPAddress.Loopback))
{
return AuthenticationSchemes.None;
}
else
{
return AuthenticationSchemes.IntegratedWindowsAuthentication;
}
}

Remarks
Note

If you want the same authentication protocol to be used for all requests handled by a particular instance of
HttpListener, you do not need to set this property. To specify a protocol to be used for all client requests, use the
AuthenticationSchemes property.
If the client has not specified authentication information in its headers, the HttpListener calls the specified delegate for
each unauthenticated incoming request to determine which, if any, protocol to use to authenticate the client. The
GetContext and EndGetContext methods return an incoming request only if the HttpListener successfully
authenticated the request. If a request cannot be authenticated, the HttpListener automatically sends back a 401
response. You can get the identity of a successfully authenticated client using the HttpRequest.LogonUserIdentity
property.
The ability to delegate the choice of authentication protocol to an application-specific method is useful if you want an
instance of HttpListener to use different authentication protocols depending on the characteristics of the requests it
receives (for example, the request's Url or UserHostAddress property).
Note

To set this property to enable Digest, NTLM, or Negotiate requires the SecurityPermission, ControlPrincipal.
HttpListener.BeginGetContext HttpListener.BeginGet
Context
I n this Article
Begins asynchronously retrieving an incoming request.

public IAsyncResult BeginGetContext (AsyncCallback callback, object state);


member this.BeginGetContext : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when a client request is available.
state Object Object
A user-defined object that contains information about the operation. This object is passed to the callback delegate
when the operation completes.
Returns
IAsyncResult IAsyncResult
An IAsyncResult object that indicates the status of the asynchronous operation.
Exceptions
HttpListenerException HttpListenerException
A Win32 function call failed. Check the exception's ErrorCode property to determine the cause of the exception.
InvalidOperationException InvalidOperationException
This object has not been started or is currently stopped.
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates using the BeginGetContext method to specify a callback method that will
handle incoming client requests.
public static void NonblockingListener(string [] prefixes)
{
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback),listener);
// Applications can do some work here while waiting for the
// request. If no work can be done until you have processed a request,
// use a wait handle to prevent this thread from terminating
// while the asynchronous operation completes.
Console.WriteLine("Waiting for request to be processed asyncronously.");
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}

The following code example implements a callback method.

public static void ListenerCallback(IAsyncResult result)


{
HttpListener listener = (HttpListener) result.AsyncState;
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
}

Remarks
The BeginGetContext method begins an asynchronous (non-blocking) call to receive incoming client requests. Before
calling this method, you must call the Start method and add at least one Uniform Resource Identifier (URI) prefix to
listen for by adding the URI strings to the HttpListenerPrefixCollection returned by the Prefixes property.
The asynchronous operation must be completed by calling the EndGetContext method. Typically, the method is
invoked by the callback delegate.
This method does not block while the operation completes. To get an incoming request and block until the operation
completes, call the GetContext method.
For detailed information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously
HttpListener.Close HttpListener.Close
I n this Article
Shuts down the HttpListener.
public void Close ();
member this.Close : unit -> unit

Examples
The following code example demonstrates calling the Close method:

public static void NonblockingListener(string [] prefixes)


{
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback),listener);
// Applications can do some work here while waiting for the
// request. If no work can be done until you have processed a request,
// use a wait handle to prevent this thread from terminating
// while the asynchronous operation completes.
Console.WriteLine("Waiting for request to be processed asyncronously.");
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}

Remarks
After calling this method, you can no longer use the HttpListener object. To temporarily pause an HttpListener object,
use the Stop method.
This method shut downs the HttpListener object without processing queued requests. Any pending requests are
unable to complete.
HttpListener.DefaultServiceNames HttpListener.Default
ServiceNames
I n this Article
Gets a default list of Service Provider Names (SPNs) as determined by registered prefixes.

public System.Security.Authentication.ExtendedProtection.ServiceNameCollection DefaultServiceNames {


get; }
member this.DefaultServiceNames :
System.Security.Authentication.ExtendedProtection.ServiceNameCollection

Returns
ServiceNameCollection ServiceNameCollection
A ServiceNameCollection that contains a list of SPNs.

Remarks
The DefaultServiceNames property is used with integrated Windows authentication to provide extended protection.
The list of SPNs is initialized from the Prefixes property when accessed and cleared when new prefixes are added to
the Prefixes property.
The DefaultServiceNames property is used if an application doesn't set the CustomServiceNames property on its
extended protection policy.
The ServiceNameCollection that is retrieved with the DefaultServiceNames property is built from the Prefixes
property according to the following rules:
1. If the hostname is "+", "*", or an IPv4 or IPv6 literal (equivalent to "*" but restricted to a specific local interface), the
following SPN is added:
"HTTP/" plus the fully qualified domain name of the computer.
1. If the hostname contains no dots (no domains or subdomains), an attempt is made to resolve the fully-qualified
domain name using DNS (the same behavior used by HttpWebRequest). If the fully-qualified domain name can be
resolved, the following SPNs are added:
"HTTP/" plus the hostname (the short name).
"HTTP/" plus the fully qualified domain name for the hostname.
1. If the hostname contains not dots (no domains or subdomains) and a fully-qualified domain name can't be resolved,
the following SPN is added:
"HTTP/" plus the hostname.
1. If the hostname contains dots (domains or subdomains), the following SPN is added:
"HTTP/" plus the hostname.
The DefaultServiceNames property can be used by an application to review the list of default SPNs which will be used
for authentication if no custom list is supplied. If other SPNs are needed, an application can add them using one of the
Merge methods.
It is not safe when using extended protection to make policy decisions based on the requested URL, since this can be
spoofed. Rather, applications should rely on the LocalEndPoint or RemoteEndPoint properties to make such policy
decisions.
See ExtendedProtectionPolicyExtendedProtectionPolicy
Also ExtendedProtectionSelectorDelegateExtendedProtectionSelectorDelegate
HttpListener.ExtendedProtectionSelectorHttpListener.ExtendedProtectionSelector
ExtendedProtectionPolicyExtendedProtectionPolicy
Integrated Windows Authentication with Extended Protection
HttpListener.EndGetContext HttpListener.EndGetContext
I n this Article
Completes an asynchronous operation to retrieve an incoming client request.
public System.Net.HttpListenerContext EndGetContext (IAsyncResult asyncResult);
member this.EndGetContext : IAsyncResult -> System.Net.HttpListenerContext

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult object that was obtained when the asynchronous operation was started.
Returns
HttpListenerContext HttpListenerContext
An HttpListenerContext object that represents the client request.
Exceptions
ArgumentException ArgumentException
asyncResult was not obtained by calling the BeginGetContext(AsyncCallback, Object) method.
ArgumentNullException ArgumentNullException
asyncResult is null .
HttpListenerException HttpListenerException
A Win32 function call failed. Check the exception's ErrorCode property to determine the cause of the exception.
InvalidOperationException InvalidOperationException
The EndGetContext(IAsyncResult) method was already called for the specified asyncResult object.
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example shows the implementation of a callback method that calls the EndGetContext method.
public static void ListenerCallback(IAsyncResult result)
{
HttpListener listener = (HttpListener) result.AsyncState;
// Call EndGetContext to complete the asynchronous operation.
HttpListenerContext context = listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
}

Remarks
The EndGetContext method is called, usually within an application-defined callback method invoked by a delegate, to
obtain the HttpListenerContext object that contains an incoming client request and its associated response. This
method completes an operation previously started by calling the BeginGetContext method. If the operation has not
completed, this method blocks until it does.
Because calling the EndGetContext method requires the HttpListener object, this object is typically passed into a
callback method by using the state object passed into the BeginGetContext method. You can obtain this state object by
using the AsyncState property of the asyncResult object.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods
Asynchronously
HttpListener.ExtendedProtectionPolicy HttpListener.
ExtendedProtectionPolicy
I n this Article
Gets or sets the ExtendedProtectionPolicy to use for extended protection for a session.

public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy
ExtendedProtectionPolicy { get; set; }
member this.ExtendedProtectionPolicy :
System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy with get, set

Returns
ExtendedProtectionPolicy ExtendedProtectionPolicy
A ExtendedProtectionPolicy that specifies the policy to use for extended protection.
Exceptions
ArgumentException ArgumentException
An attempt was made to set the ExtendedProtectionPolicy property, but the CustomChannelBinding property was not
null .

ArgumentNullException ArgumentNullException
An attempt was made to set the ExtendedProtectionPolicy property to null .
InvalidOperationException InvalidOperationException
An attempt was made to set the ExtendedProtectionPolicy property after the Start() method was already called.
ObjectDisposedException ObjectDisposedException
This object is closed.
PlatformNotSupportedException PlatformNotSupportedException
The PolicyEnforcement property was set to Always on a platform that does not support extended protection.

Remarks
The ExtendedProtectionPolicy property is used with integrated Windows authentication to provide extended
protection. The ExtendedProtectionPolicy property allows the configuration of the extended protection policy for the
whole HttpListener session. The ExtendedProtectionSelectorDelegate property allows the configuration of the
extended protection policy for each individual request.
The CustomChannelBinding property must be null . The HttpListener instance gets the Channel Binding Token (CBT)
directly from its own TLS session if there is one.
See DefaultServiceNamesDefaultServiceNames
Also ExtendedProtectionSelectorDelegateExtendedProtectionSelectorDelegate
HttpListener.ExtendedProtectionSelectorHttpListener.ExtendedProtectionSelector
ExtendedProtectionPolicyExtendedProtectionPolicy
Integrated Windows Authentication with Extended Protection
HttpListener.ExtendedProtectionSelectorDelegate Http
Listener.ExtendedProtectionSelectorDelegate
I n this Article
Gets or sets the delegate called to determine the ExtendedProtectionPolicy to use for each request.

public System.Net.HttpListener.ExtendedProtectionSelector ExtendedProtectionSelectorDelegate { get;


set; }
member this.ExtendedProtectionSelectorDelegate : System.Net.HttpListener.ExtendedProtectionSelector
with get, set

Returns
HttpListener.ExtendedProtectionSelector HttpListener.ExtendedProtectionSelector
A ExtendedProtectionPolicy that specifies the policy to use for extended protection.
Exceptions
ArgumentException ArgumentException
An attempt was made to set the ExtendedProtectionSelectorDelegate property, but the CustomChannelBinding
property must be null .
ArgumentNullException ArgumentNullException
An attempt was made to set the ExtendedProtectionSelectorDelegate property to null .
InvalidOperationException InvalidOperationException
An attempt was made to set the ExtendedProtectionSelectorDelegate property after the Start() method was already
called.
ObjectDisposedException ObjectDisposedException
This object is closed.
PlatformNotSupportedException PlatformNotSupportedException
An attempt was made to set the ExtendedProtectionSelectorDelegate property on a platform that does not support
extended protection.

Remarks
The ExtendedProtectionPolicy property is used with integrated Windows authentication to provide extended
protection. The ExtendedProtectionPolicy property allows the configuration of the extended protection policy for the
whole HttpListener session. The ExtendedProtectionSelectorDelegate property allows the configuration of the
extended protection policy per individual request.
The CustomChannelBinding property must be null . The HttpListener instance gets the Channel Binding Token (CBT)
directly from its own TLS session if there is one.
For each request, the delegate can choose the settings that the HttpListener instance will use to provide extended
protection.
If a delegate returns null for this property, this represents a ExtendedProtectionPolicy which the PolicyEnforcement
property set to Never.
See DefaultServiceNamesDefaultServiceNames
Also ExtendedProtectionPolicyExtendedProtectionPolicy
HttpListener.ExtendedProtectionSelectorHttpListener.ExtendedProtectionSelector
ExtendedProtectionPolicyExtendedProtectionPolicy
Integrated Windows Authentication with Extended Protection
HttpListener.GetContext HttpListener.GetContext
I n this Article
Waits for an incoming request and returns when one is received.
public System.Net.HttpListenerContext GetContext ();
member this.GetContext : unit -> System.Net.HttpListenerContext

Returns
HttpListenerContext HttpListenerContext
An HttpListenerContext object that represents a client request.
Exceptions
HttpListenerException HttpListenerException
A Win32 function call failed. Check the exception's ErrorCode property to determine the cause of the exception.
InvalidOperationException InvalidOperationException
This object has not been started or is currently stopped.
-or-
The HttpListener does not have any Uniform Resource Identifier (URI) prefixes to respond to.
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates calling this method.
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}

Remarks
Before calling this method, you must call the Start method and add at least one URI prefix to listen for by adding the
URI strings to the HttpListenerPrefixCollection returned by the Prefixes property. For a detailed description of prefixes,
see the HttpListener class overview.
This method blocks while waiting for an incoming request. If you want incoming requests to be processed
asynchronously (on separate threads) so that your application does not block, use the BeginGetContext method.
HttpListener.GetContextAsync HttpListener.GetContext
Async
I n this Article
Waits for an incoming request as an asynchronous operation.

public System.Threading.Tasks.Task<System.Net.HttpListenerContext> GetContextAsync ();


member this.GetContextAsync : unit -> System.Threading.Tasks.Task<System.Net.HttpListenerContext>

Returns
Task<HttpListenerContext>
The task object representing the asynchronous operation. The Result property on the task object returns an
HttpListenerContext object that represents a client request.

Remarks
This operation will not block. The returned Task<TResult> object will complete when the incoming request has been
received.
Before calling this method, you must call the Start method and add at least one URI prefix to listen for by adding the
URI strings to the HttpListenerPrefixCollection returned by the Prefixes property. For a detailed description of prefixes,
see the HttpListener class overview.
See HttpListenerContextHttpListenerContext
Also
HttpListener
I n this Article
Initializes a new instance of the HttpListener class.
public HttpListener ();

Exceptions
PlatformNotSupportedException
This class cannot be used on the current operating system. Windows Server 2003 or Windows XP SP2 is required to
use instances of this class.

Examples
The following code example demonstrates using the HttpListener constructor to create a new HttpListener object. For
the complete example, see the HttpListener class topic.
// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();

Remarks
Before using the instance returned by this constructor, you must invoke its Start method.
HttpListener.IDisposable.Dispose
I n this Article
Releases the resources held by this HttpListener object.
void IDisposable.Dispose ();

Remarks
Applications should use the Close method instead of calling this method.
HttpListener.IgnoreWriteExceptions HttpListener.Ignore
WriteExceptions
I n this Article
Gets or sets a Boolean value that specifies whether your application receives exceptions that occur when an
HttpListener sends the response to the client.
public bool IgnoreWriteExceptions { get; set; }
member this.IgnoreWriteExceptions : bool with get, set

Returns
Boolean Boolean
true if this HttpListener should not return exceptions that occur when sending the response to the client; otherwise,
false . The default value is false .

Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example demonstrates setting this property.
public static void SimpleListenerWithUnsafeAuthentication(string[] prefixes)
{
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
// Specify Negotiate as the authentication scheme.
listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
// If NTLM is used, we will allow multiple requests on the same
// connection to use the authentication information of first request.
// This improves performance but does reduce the security of your
// application.
listener.UnsafeConnectionNtlmAuthentication = true;
// This listener does not want to receive exceptions
// that occur when sending the response to the client.
listener.IgnoreWriteExceptions = true;
Console.WriteLine("Listening...");
// ... process requests here.

listener.Close();
}

Remarks
Set this property to true if your application does not require that a response is successfully sent to each client.
HttpListener.IsListening HttpListener.IsListening
I n this Article
Gets a value that indicates whether HttpListener has been started.
public bool IsListening { get; }
member this.IsListening : bool

Returns
Boolean Boolean
true if the HttpListener was started; otherwise, false .

Examples
The following code example demonstrates using this property to determine the listening state of an instance.
public static void DisplayPrefixesAndState(HttpListener listener)
{
// List the prefixes to which the server listens.
HttpListenerPrefixCollection prefixes = listener.Prefixes;
if (prefixes.Count == 0)
{
Console.WriteLine("There are no prefixes.");
}
foreach(string prefix in prefixes)
{
Console.WriteLine(prefix);
}
// Show the listening state.
if (listener.IsListening)
{
Console.WriteLine("The server is listening.");
}
}

Remarks
To start an HttpListener, call the Start method.
HttpListener.IsSupported HttpListener.IsSupported
I n this Article
Gets a value that indicates whether HttpListener can be used with the current operating system.
public static bool IsSupported { get; }
member this.IsSupported : bool

Returns
Boolean Boolean
true if HttpListener is supported; otherwise, false .

Examples
The following code example demonstrates the use of the IsSupported property to detect whether an HttpListener
object can be used with the current operating system.
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}

Remarks
This class is available only on computers running the Windows XP SP2 or Windows Server 2003 operating systems.
HttpListener.Prefixes HttpListener.Prefixes
I n this Article
Gets the Uniform Resource Identifier (URI) prefixes handled by this HttpListener object.
public System.Net.HttpListenerPrefixCollection Prefixes { get; }
member this.Prefixes : System.Net.HttpListenerPrefixCollection

Returns
HttpListenerPrefixCollection HttpListenerPrefixCollection
An HttpListenerPrefixCollection that contains the URI prefixes that this HttpListener object is configured to handle.
Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example demonstrates using the Prefixes property to obtain and print the URI prefixes that are
handled.
public static void DisplayPrefixesAndState(HttpListener listener)
{
// List the prefixes to which the server listens.
HttpListenerPrefixCollection prefixes = listener.Prefixes;
if (prefixes.Count == 0)
{
Console.WriteLine("There are no prefixes.");
}
foreach(string prefix in prefixes)
{
Console.WriteLine(prefix);
}
// Show the listening state.
if (listener.IsListening)
{
Console.WriteLine("The server is listening.");
}
}

Remarks
The prefixes are in canonical form. For a detailed description of prefixes, see the HttpListener class overview.
HttpListener.Realm HttpListener.Realm
I n this Article
Gets or sets the realm, or resource partition, associated with this HttpListener object.
public string Realm { get; set; }
member this.Realm : string with get, set

Returns
String String
A String value that contains the name of the realm associated with the HttpListener object.
Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example demonstrates setting the Realm property.
public static void ConfigureListener1(HttpListener listener)
{
// Specify an authentication realm.
listener.Realm = "ExampleRealm";
}

Remarks
Servers use realms to partition protected resources; each partition can have its own authentication scheme and/or
authorization database. Realms are used only for basic and digest authentication. After a client successfully
authenticates, the authentication is valid for all resources in a given realm. For a detailed description of realms, see RFC
2617 at https://www.ietf.org/.
An instance of HttpListener has only one associated realm.
HttpListener.Start HttpListener.Start
I n this Article
Allows this instance to receive incoming requests.
public void Start ();
member this.Start : unit -> unit

Exceptions
HttpListenerException HttpListenerException
A Win32 function call failed. Check the exception's ErrorCode property to determine the cause of the exception.
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates using the Start method to begin processing incoming requests.

public static void NonblockingListener(string [] prefixes)


{
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
IAsyncResult result = listener.BeginGetContext(new AsyncCallback(ListenerCallback),listener);
// Applications can do some work here while waiting for the
// request. If no work can be done until you have processed a request,
// use a wait handle to prevent this thread from terminating
// while the asynchronous operation completes.
Console.WriteLine("Waiting for request to be processed asyncronously.");
result.AsyncWaitHandle.WaitOne();
Console.WriteLine("Request processed asyncronously.");
listener.Close();
}

Remarks
This method must be called before you call the GetContext or BeginGetContext method.
After you have started an HttpListener object, you can use the Stop method to stop it.
Note

If this listener instance uses https, you must install and select a Server Certificate. Otherwise, an HttpWebRequest
query of this HttpListener will fail with an unexpected close of the connection. You can configure Server Certificates
and other listener options by using HttpCfg.exe. See http://msdn.microsoft.com/library/default.asp?
url=/library/http/http/httpcfg_exe.asp for more details.
HttpListener.Stop HttpListener.Stop
I n this Article
Causes this instance to stop receiving incoming requests.
public void Stop ();
member this.Stop : unit -> unit

Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example demonstrates using the Stop method to stop processing incoming requests.
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}

Remarks
If this instance is already stopped, calling this method has no effect.
After you have stopped an HttpListener object, you can use the Start method to restart it.
HttpListener.TimeoutManager HttpListener.Timeout
Manager
I n this Article
The timeout manager for this HttpListener instance.

public System.Net.HttpListenerTimeoutManager TimeoutManager { get; }


member this.TimeoutManager : System.Net.HttpListenerTimeoutManager

Returns
HttpListenerTimeoutManager HttpListenerTimeoutManager
The timeout manager for this HttpListener instance.

Remarks
The timeout manager defines the connection timeout limits for this HttpListener instance.
HttpListener.UnsafeConnectionNtlmAuthentication Http
Listener.UnsafeConnectionNtlmAuthentication
I n this Article
Gets or sets a Boolean value that controls whether, when NTLM is used, additional requests using the same
Transmission Control Protocol (TCP ) connection are required to authenticate.
public bool UnsafeConnectionNtlmAuthentication { get; set; }
member this.UnsafeConnectionNtlmAuthentication : bool with get, set

Returns
Boolean Boolean
true if the IIdentity of the first request will be used for subsequent requests on the same connection; otherwise,
false . The default value is false .

Exceptions
ObjectDisposedException ObjectDisposedException
This object has been closed.

Examples
The following code example demonstrates setting this property.
public static void SimpleListenerWithUnsafeAuthentication(string[] prefixes)
{
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
// Specify Negotiate as the authentication scheme.
listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
// If NTLM is used, we will allow multiple requests on the same
// connection to use the authentication information of first request.
// This improves performance but does reduce the security of your
// application.
listener.UnsafeConnectionNtlmAuthentication = true;
// This listener does not want to receive exceptions
// that occur when sending the response to the client.
listener.IgnoreWriteExceptions = true;
Console.WriteLine("Listening...");
// ... process requests here.

listener.Close();
}

Remarks
When this property is set to true and the first request over a particular TCP connection is authenticated using NTLM,
subsequent requests over the same TCP connection are processed using the authentication information (IIdentity) of
the initial request.
This property has no effect when NTLM is not the authentication protocol. When Negotiate is specified as the
authentication protocol, this property has an effect only if NTLM is the actual protocol used for authentication.
Note

While setting this property to true increases performance because the HttpListener does not send additional NTLM
authentication challenges, there is a security risk in not requiring all requests to provide authentication information.
You must determine whether the increase in performance is worth this risk.
HttpListener.ExtendedProtectionSelector HttpListener.
ExtendedProtectionSelector Delegate
A delegate called to determine the ExtendedProtectionPolicy to use for each HttpListener request.

D eclaration
public delegate System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy
HttpListener.ExtendedProtectionSelector(HttpListenerRequest request);
type HttpListener.ExtendedProtectionSelector = delegate of HttpListenerRequest ->
ExtendedProtectionPolicy

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
The HttpListener.ExtendedProtectionSelector class is used with integrated Windows authentication to provide
extended protection. For each request, the delegate can choose the settings that the HttpListener instance will use to
provide extended protection.

See Also
HttpListenerBasicIdentity HttpListenerBasicIdentity Class
Holds the user name and password from a basic authentication request.

D eclaration
public class HttpListenerBasicIdentity : System.Security.Principal.GenericIdentity
type HttpListenerBasicIdentity = class
inherit GenericIdentity

I nheritance H ierarchy
Object Object
GenericIdentity GenericIdentity

Constructors
HttpListenerBasicIdentity(String, String)
HttpListenerBasicIdentity(String, String)

Initializes a new instance of the HttpListenerBasicIdentity class using the specified user name and password.

Properties
Password
Password

Indicates the password from a basic authentication attempt.


HttpListenerBasicIdentity HttpListenerBasicIdentity
I n this Article
Initializes a new instance of the HttpListenerBasicIdentity class using the specified user name and password.
public HttpListenerBasicIdentity (string username, string password);
new System.Net.HttpListenerBasicIdentity : string * string -> System.Net.HttpListenerBasicIdentity

Parameters
username String String
The user name.
password String String
The password.

Remarks
This constructor is called by the HttpListener class when performing basic authentication.
HttpListenerBasicIdentity.Password HttpListenerBasic
Identity.Password
I n this Article
Indicates the password from a basic authentication attempt.

public virtual string Password { get; }


member this.Password : string

Returns
String String
A String that holds the password.
HttpListenerContext HttpListenerContext Class
Provides access to the request and response objects used by the HttpListener class. This class cannot be inherited.

D eclaration
public sealed class HttpListenerContext
type HttpListenerContext = class

I nheritance H ierarchy
Object Object

Remarks
This class provides the information related to a client's Hypertext Transfer Protocol (HTTP ) request being processed by
an HttpListener object. This class also has methods that allow an HttpListener object to accept a WebSocket
connection.
The GetContext method returns instances of the HttpListenerContext class. To get the object that represents the client
request, use the Request property. To get the object that represents the response that will be sent to the client by the
HttpListener, use the Response property. To get user information about the client sending the request, such as its login
name and whether it has been authenticated, you can query the properties in the IPrincipal object returned by the User
property.
Closing an HttpListenerContext object sends the response to the client and frees any resources used by the
HttpListenerContext. Aborting an HttpListenerContext object discards the response to the client if it has not already
been sent, and frees any resources used by the HttpListenerContext. After closing or aborting an HttpListenerContext
object, you cannot reference its methods or properties. If you do so, you will receive an ObjectDisposedException
exception.

Properties
Request
Request

Gets the HttpListenerRequest that represents a client's request for a resource.

Response
Response

Gets the HttpListenerResponse object that will be sent to the client in response to the client's request.

User
User

Gets an object used to obtain identity, authentication information, and security roles for the client whose request is
represented by this HttpListenerContext object.

Methods
AcceptWebSocketAsync(String)
AcceptWebSocketAsync(String)

Accept a WebSocket connection as an asynchronous operation.

AcceptWebSocketAsync(String, TimeSpan)
AcceptWebSocketAsync(String, TimeSpan)

Accept a WebSocket connection specifying the supported WebSocket sub-protocol and WebSocket keep-alive
interval as an asynchronous operation.

AcceptWebSocketAsync(String, Int32, TimeSpan)


AcceptWebSocketAsync(String, Int32, TimeSpan)

Accept a WebSocket connection specifying the supported WebSocket sub-protocol, receive buffer size, and
WebSocket keep-alive interval as an asynchronous operation.

AcceptWebSocketAsync(String, Int32, TimeSpan, ArraySegment<Byte>)


AcceptWebSocketAsync(String, Int32, TimeSpan, ArraySegment<Byte>)

Accept a WebSocket connection specifying the supported WebSocket sub-protocol, receive buffer size, WebSocket
keep-alive interval, and the internal buffer as an asynchronous operation.

See Also
HttpListenerRequest HttpListenerRequest
HttpListenerResponse HttpListenerResponse
HttpListenerContext.AcceptWebSocketAsync Http
ListenerContext.AcceptWebSocketAsync
I n this Article

Overloads
AcceptWebSocketAsync(String) AcceptWebSocketAsync(String)
Accept a WebSocket connection as an asynchronous
operation.

AcceptWebSocketAsync(String, TimeSpan) AcceptWebSocket


Async(String, TimeSpan) Accept a WebSocket connection specifying the supported
WebSocket sub-protocol and WebSocket keep-alive interval as
an asynchronous operation.

AcceptWebSocketAsync(String, Int32, TimeSpan) AcceptWeb


SocketAsync(String, Int32, TimeSpan) Accept a WebSocket connection specifying the supported
WebSocket sub-protocol, receive buffer size, and WebSocket
keep-alive interval as an asynchronous operation.

AcceptWebSocketAsync(String, Int32, TimeSpan, Array


Segment<Byte>) AcceptWebSocketAsync(String, Int32, Time Accept a WebSocket connection specifying the supported
Span, ArraySegment<Byte>) WebSocket sub-protocol, receive buffer size, WebSocket keep-
alive interval, and the internal buffer as an asynchronous
operation.

AcceptWebSocketAsync(String) AcceptWebSocketAsync(String)
Accept a WebSocket connection as an asynchronous operation.
public System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>
AcceptWebSocketAsync (string subProtocol);
member this.AcceptWebSocketAsync : string ->
System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>

Parameters
subProtocol String String
The supported WebSocket sub-protocol.
Returns
Task<HttpListenerWebSocketContext>
The task object representing the asynchronous operation. The Result property on the task object returns an
HttpListenerWebSocketContext object.
Exceptions
ArgumentException ArgumentException
subProtocol is an empty string
-or-
subProtocol contains illegal characters.
WebSocketException WebSocketException
An error occurred when sending the response to complete the WebSocket handshake.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the WebSocket connection has
been accepted.
The size of the receive buffer is 16,385 bytes. The WebSocket keep-alive interval is set to the default value of 30,000
(30 seconds).

See HttpListenerWebSocketContextHttpListenerWebSocketContext
Also

AcceptWebSocketAsync(String, TimeSpan)
AcceptWebSocketAsync(String, TimeSpan)
Accept a WebSocket connection specifying the supported WebSocket sub-protocol and WebSocket keep-alive interval
as an asynchronous operation.
public System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>
AcceptWebSocketAsync (string subProtocol, TimeSpan keepAliveInterval);
member this.AcceptWebSocketAsync : string * TimeSpan ->
System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>

Parameters
subProtocol String String
The supported WebSocket sub-protocol.
keepAliveInterval TimeSpan TimeSpan
The WebSocket protocol keep-alive interval in milliseconds.
Returns
Task<HttpListenerWebSocketContext>
The task object representing the asynchronous operation. The Result property on the task object returns an
HttpListenerWebSocketContext object.
Exceptions
ArgumentException ArgumentException
subProtocol is an empty string
-or-
subProtocol contains illegal characters.

ArgumentOutOfRangeException ArgumentOutOfRangeException
keepAliveInterval is too small.

WebSocketException WebSocketException
An error occurred when sending the response to complete the WebSocket handshake.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the WebSocket connection has
been accepted.
The size of the receive buffer is 16,385 bytes.
See HttpListenerWebSocketContextHttpListenerWebSocketContext
Also

AcceptWebSocketAsync(String, Int32, TimeSpan)


AcceptWebSocketAsync(String, Int32, TimeSpan)
Accept a WebSocket connection specifying the supported WebSocket sub-protocol, receive buffer size, and WebSocket
keep-alive interval as an asynchronous operation.
public System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>
AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval);
member this.AcceptWebSocketAsync : string * int * TimeSpan ->
System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>

Parameters
subProtocol String String
The supported WebSocket sub-protocol.
receiveBufferSize Int32 Int32
The receive buffer size in bytes.
keepAliveInterval TimeSpan TimeSpan
The WebSocket protocol keep-alive interval in milliseconds.
Returns
Task<HttpListenerWebSocketContext>
The task object representing the asynchronous operation. The Result property on the task object returns an
HttpListenerWebSocketContext object.
Exceptions
ArgumentException ArgumentException
subProtocol is an empty string
-or-
subProtocol contains illegal characters.

ArgumentOutOfRangeException ArgumentOutOfRangeException
keepAliveInterval is too small.
-or-
receiveBufferSize is less than 16 bytes
-or-
receiveBufferSize is greater than 64K bytes.

WebSocketException WebSocketException
An error occurred when sending the response to complete the WebSocket handshake.
Remarks
This operation will not block. The returned Task<TResult> > object will complete after the WebSocket connection has
been accepted.
See HttpListenerWebSocketContextHttpListenerWebSocketContext
Also

AcceptWebSocketAsync(String, Int32, TimeSpan,


ArraySegment<Byte>) AcceptWebSocketAsync(String, Int32,
TimeSpan, ArraySegment<Byte>)
Accept a WebSocket connection specifying the supported WebSocket sub-protocol, receive buffer size, WebSocket
keep-alive interval, and the internal buffer as an asynchronous operation.

public System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>
AcceptWebSocketAsync (string subProtocol, int receiveBufferSize, TimeSpan keepAliveInterval,
ArraySegment<byte> internalBuffer);
member this.AcceptWebSocketAsync : string * int * TimeSpan * ArraySegment<byte> ->
System.Threading.Tasks.Task<System.Net.WebSockets.HttpListenerWebSocketContext>

Parameters
subProtocol String String
The supported WebSocket sub-protocol.
receiveBufferSize Int32 Int32
The receive buffer size in bytes.
keepAliveInterval TimeSpan TimeSpan
The WebSocket protocol keep-alive interval in milliseconds.
internalBuffer ArraySegment<Byte>
An internal buffer to use for this operation.
Returns
Task<HttpListenerWebSocketContext>
The task object representing the asynchronous operation. The Result property on the task object returns an
HttpListenerWebSocketContext object.
Exceptions
ArgumentException ArgumentException
subProtocol is an empty string
-or-
subProtocol contains illegal characters.

ArgumentOutOfRangeException ArgumentOutOfRangeException
keepAliveInterval is too small.
-or-
receiveBufferSize is less than 16 bytes
-or-
receiveBufferSize is greater than 64K bytes.
WebSocketException WebSocketException
An error occurred when sending the response to complete the WebSocket handshake.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the WebSocket connection has
been accepted.
See HttpListenerWebSocketContextHttpListenerWebSocketContext
Also
HttpListenerContext.Request HttpListenerContext.
Request
I n this Article
Gets the HttpListenerRequest that represents a client's request for a resource.

public System.Net.HttpListenerRequest Request { get; }


member this.Request : System.Net.HttpListenerRequest

Returns
HttpListenerRequest HttpListenerRequest
An HttpListenerRequest object that represents the client request.

Examples
The following code example demonstrates calling this method. The listener variable holds an HttpListener object.
// This example requires the System and System.Net namespaces.
public static string ClientInformation(HttpListenerContext context)
{
System.Security.Principal.IPrincipal user = context.User;
System.Security.Principal.IIdentity id = user.Identity;
if (id == null)
{
return "Client authentication is not enabled for this Web server.";
}

string display;
if (id.IsAuthenticated)
{
display = String.Format("{0} was authenticated using {1}", id.Name,
id.AuthenticationType);
}
else
{
display = String.Format("{0} was not authenticated", id.Name);
}
return display;
}

public static void SimpleListenerWithAuthentication(string[] prefixes)


{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}

// URI prefixes are required,


// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
// Specify Negotiate as the authentication scheme.
listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
Console.WriteLine("Listening...");
// GetContext blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string clientInformation = ClientInformation(context);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("<HTML><BODY> " + clientInformation + "
</BODY></HTML>");
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
output.Close();
listener.Stop();
}
Remarks
If you close this HttpListenerContext, it will send the response to the client, close the HttpListenerResponse that
contains the response, and close the HttpListenerRequest object returned by this property.
HttpListenerContext.Response HttpListenerContext.
Response
I n this Article
Gets the HttpListenerResponse object that will be sent to the client in response to the client's request.

public System.Net.HttpListenerResponse Response { get; }


member this.Response : System.Net.HttpListenerResponse

Returns
HttpListenerResponse HttpListenerResponse
An HttpListenerResponse object used to send a response back to the client.

Examples
The following code example demonstrates getting the response to a client's request and adding the response body.
// This example requires the System and System.Net namespaces.
public static string ClientInformation(HttpListenerContext context)
{
System.Security.Principal.IPrincipal user = context.User;
System.Security.Principal.IIdentity id = user.Identity;
if (id == null)
{
return "Client authentication is not enabled for this Web server.";
}

string display;
if (id.IsAuthenticated)
{
display = String.Format("{0} was authenticated using {1}", id.Name,
id.AuthenticationType);
}
else
{
display = String.Format("{0} was not authenticated", id.Name);
}
return display;
}

public static void SimpleListenerWithAuthentication(string[] prefixes)


{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}

// URI prefixes are required,


// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
// Specify Negotiate as the authentication scheme.
listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
Console.WriteLine("Listening...");
// GetContext blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string clientInformation = ClientInformation(context);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("<HTML><BODY> " + clientInformation + "
</BODY></HTML>");
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
output.Close();
listener.Stop();
}
Remarks
Your application configures the response by setting properties in the HttpListenerResponse object returned by this
property. After configuring the response, you send it to the client by closing the response, or by closing this
HttpListenerContext object.
HttpListenerContext.User HttpListenerContext.User
I n this Article
Gets an object used to obtain identity, authentication information, and security roles for the client whose request is
represented by this HttpListenerContext object.

public System.Security.Principal.IPrincipal User { get; }


member this.User : System.Security.Principal.IPrincipal

Returns
IPrincipal IPrincipal
An IPrincipal object that describes the client, or null if the HttpListener that supplied this HttpListenerContext does
not require authentication.

Examples
The following code example demonstrates accessing identity and authentication information about the client, and
returning it to the client in the response.
public static string ClientInformation(HttpListenerContext context)
{
System.Security.Principal.IPrincipal user = context.User;
System.Security.Principal.IIdentity id = user.Identity;
if (id == null)
{
return "Client authentication is not enabled for this Web server.";
}

string display;
if (id.IsAuthenticated)
{
display = String.Format("{0} was authenticated using {1}", id.Name,
id.AuthenticationType);
}
else
{
display = String.Format("{0} was not authenticated", id.Name);
}
return display;
}

Remarks
An HttpListener indicates that it requires authentication using the AuthenticationSchemes property or by specifying an
AuthenticationSchemeSelector delegate using the AuthenticationSchemeSelectorDelegate property.
To determine the client's login name and authentication information, check the IPrincipal.Identity property in the object
returned by this property.
HttpListenerException HttpListenerException Class
The exception that is thrown when an error occurs processing an HTTP request.

D eclaration
[System.Serializable]
public class HttpListenerException : System.ComponentModel.Win32Exception
type HttpListenerException = class
inherit Win32Exception

I nheritance H ierarchy
Object Object
Exception Exception
SystemException SystemException
ExternalException ExternalException
Win32Exception Win32Exception

Remarks
This exception is thrown by the HttpListener class and its associated classes when an error occurs during initialization
of the HttpListener or while creating or sending a response to an HTTP request. For example, this exception is thrown if
the HttpListener attempts to register a Uniform Resource Identifier (URI) prefix that is already registered.
Associated Tips
Make sure you are not attempting to register a URI prefix that is already registered.
If the URI prefix is already registered, this exception will occur.
Make sure your HTTP request is valid.
This exception is thrown by the HttpListener class and its associated classes when an error occurs during the
initialization of the HttpListener or while creating or sending a response to an HTTP request.
If you are using the HttpListenerPrefixCollection.Add method, make sure the uriPrefix has not been already
added.
This exception will be thrown if another HttpListener has already added the prefix uriPrefix .

Constructors
HttpListenerException()
HttpListenerException()

Initializes a new instance of the HttpListenerException class.

HttpListenerException(Int32)
HttpListenerException(Int32)

Initializes a new instance of the HttpListenerException class using the specified error code.

HttpListenerException(Int32, String)
HttpListenerException(Int32, String)
Initializes a new instance of the HttpListenerException class using the specified error code and message.

HttpListenerException(SerializationInfo, StreamingContext)
HttpListenerException(SerializationInfo, StreamingContext)

Initializes a new instance of the HttpListenerException class from the specified instances of the SerializationInfo
and StreamingContext classes.

Properties
ErrorCode
ErrorCode

Gets a value that identifies the error that occurred.


HttpListenerException.ErrorCode HttpListenerException.
ErrorCode
I n this Article
Gets a value that identifies the error that occurred.

public override int ErrorCode { get; }


member this.ErrorCode : int

Returns
Int32 Int32
A Int32 value.

Remarks
This property returns the Windows error code associated with this exception.
HttpListenerException HttpListenerException
I n this Article

Overloads
HttpListenerException()
Initializes a new instance of the HttpListenerException class.

HttpListenerException(Int32) HttpListenerException(Int32)
Initializes a new instance of the HttpListenerException class
using the specified error code.

HttpListenerException(Int32, String) HttpListenerException(


Int32, String) Initializes a new instance of the HttpListenerException class
using the specified error code and message.

HttpListenerException(SerializationInfo, StreamingContext)
HttpListenerException(SerializationInfo, StreamingContext) Initializes a new instance of the HttpListenerException class
from the specified instances of the SerializationInfo and
StreamingContext classes.

HttpListenerException()
Initializes a new instance of the HttpListenerException class.
public HttpListenerException ();

Remarks
This constructor sets the ErrorCode and Message properties using the most recent Windows error.

HttpListenerException(Int32) HttpListenerException(Int32)
Initializes a new instance of the HttpListenerException class using the specified error code.
public HttpListenerException (int errorCode);
new System.Net.HttpListenerException : int -> System.Net.HttpListenerException

Parameters
errorCode Int32 Int32
A Int32 value that identifies the error that occurred.
Remarks
The value of errorCode is used to set the ErrorCode property.

HttpListenerException(Int32, String) HttpListenerException(Int32,


String)
Initializes a new instance of the HttpListenerException class using the specified error code and message.
public HttpListenerException (int errorCode, string message);
new System.Net.HttpListenerException : int * string -> System.Net.HttpListenerException

Parameters
errorCode Int32 Int32
A Int32 value that identifies the error that occurred.
message String String
A String that describes the error that occurred.
Remarks
The value of errorCode is used to set the ErrorCode property. The message parameter is used to set the Message
property.

HttpListenerException(SerializationInfo, StreamingContext)
HttpListenerException(SerializationInfo, StreamingContext)
Initializes a new instance of the HttpListenerException class from the specified instances of the SerializationInfo and
StreamingContext classes.
protected HttpListenerException (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.HttpListenerException : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.HttpListenerException

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo object that contains the information required to deserialize the new HttpListenerException object.
streamingContext StreamingContext StreamingContext
A StreamingContext object.
See XML and SOAP Serialization
Also
HttpListenerPrefixCollection HttpListenerPrefixCollection
Class
Represents the collection used to store Uniform Resource Identifier (URI) prefixes for HttpListener objects.

D eclaration
public class HttpListenerPrefixCollection : System.Collections.Generic.ICollection<string>,
System.Collections.Generic.IEnumerable<string>
type HttpListenerPrefixCollection = class
interface ICollection<string>
interface seq<string>
interface IEnumerable

I nheritance H ierarchy
Object Object

Remarks
The Prefixes property returns instances of this collection.

Properties
Count
Count

Gets the number of prefixes contained in the collection.

IsReadOnly
IsReadOnly

Gets a value that indicates whether access to the collection is read-only.

IsSynchronized
IsSynchronized

Gets a value that indicates whether access to the collection is synchronized (thread-safe).

Methods
Add(String)
Add(String)

Adds a Uniform Resource Identifier (URI) prefix to the collection.

Clear()
Clear()

Removes all the Uniform Resource Identifier (URI) prefixes from the collection.
Contains(String)
Contains(String)

Returns a Boolean value that indicates whether the specified prefix is contained in the collection.

CopyTo(Array, Int32)
CopyTo(Array, Int32)

Copies the contents of an HttpListenerPrefixCollection to the specified array.

CopyTo(String[], Int32)
CopyTo(String[], Int32)

Copies the contents of an HttpListenerPrefixCollection to the specified string array.

GetEnumerator()
GetEnumerator()

Returns an object that can be used to iterate through the collection.

Remove(String)
Remove(String)

Removes the specified Uniform Resource Identifier (URI) from the list of prefixes handled by the HttpListener
object.

IEnumerable.GetEnumerator()
IEnumerable.GetEnumerator()

Returns an object that can be used to iterate through the collection.


HttpListenerPrefixCollection.Add HttpListenerPrefix
Collection.Add
I n this Article
Adds a Uniform Resource Identifier (URI) prefix to the collection.

public void Add (string uriPrefix);


abstract member Add : string -> unit
override this.Add : string -> unit

Parameters
uriPrefix String String
A String that identifies the URI information that is compared in incoming requests. The prefix must be terminated with
a forward slash ("/").
Exceptions
ArgumentNullException ArgumentNullException
uriPrefix is null .
ArgumentException ArgumentException
uriPrefix does not use the http:// or https:// scheme. These are the only schemes supported for HttpListener objects.
-or-
uriPrefix is not a correctly formatted URI prefix. Make sure the string is terminated with a "/".
ObjectDisposedException ObjectDisposedException
The HttpListener associated with this collection is closed.
HttpListenerException HttpListenerException
A Windows function call failed. Check the exception's ErrorCode property to determine the cause of the exception. This
exception is thrown if another HttpListener has already added the prefix uriPrefix .

Examples
The following code example creates an HttpListener and adds user-specified prefixes to its
HttpListenerPrefixCollection.
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}

Remarks
This method adds a URI prefix to the set of prefixes managed by the associated HttpListener object. When checking
uriPrefix to ensure it is valid, case is ignored.

A URI prefix string is composed of a scheme (http or https), a host, an optional port, and an optional path, for example,
" http://www.contoso.com:8080/customerData/ ". The prefix must be terminated with a forward slash ("/"). The
HttpListener with the prefix that most closely matches a requested URI responds to the request. Multiple HttpListener
objects cannot add the same prefix. An HttpListenerException exception is thrown if an HttpListener adds a prefix that
is already in use.
When a port is specified, the host element can be replaced with " * " to indicate that the HttpListener accepts requests
sent to the port if the requested URI does not match any other prefix. For example, to receive all requests sent to port
8080 when the requested URI is not handled by any other HttpListener, the prefix is " http://*:8080/ ". Similarly, to
specify that the HttpListener accepts all requests sent to a port, replace the host element with the " + " character, "
https://+:8080/ ". The " * " and " + " characters can be present in prefixes that include paths.

Starting with .NET 4.5.3 and Windows 10, wildcard subdomains are supported in URI prefixes that are managed by an
HttpListener object. To specify a wildcard subdomain, use the "*" character as part of the hostname in a URI prefix: for
example, http://*.foo.com/ , and pass this as the argument to the HttpListenerPrefixCollection.Add method. This will
work on .NET 4.5.3 and Windows 10; in earlier versions, this would generate an HttpListenerException
HttpListenerPrefixCollection.Clear HttpListenerPrefix
Collection.Clear
I n this Article
Removes all the Uniform Resource Identifier (URI) prefixes from the collection.

public void Clear ();


abstract member Clear : unit -> unit
override this.Clear : unit -> unit

Exceptions
HttpListenerException HttpListenerException
A Windows function call failed. Check the exception's ErrorCode property to determine the cause of the exception.
ObjectDisposedException ObjectDisposedException
The HttpListener associated with this collection is closed.

Examples
The following code example removes all prefixes in an HttpListenerPrefixCollection.
public static bool RemoveAllPrefixes(HttpListener listener)
{
// Get the prefixes that the Web server is listening to.
HttpListenerPrefixCollection prefixes = listener.Prefixes;
try
{
prefixes.Clear();
}
// If the operation failed, return false.
catch
{
return false;
}
return true;
}

Remarks
After calling this method, you cannot start the associated HttpListener without adding new prefixes; if you try to do so,
an exception is thrown.
HttpListenerPrefixCollection.Contains HttpListenerPrefix
Collection.Contains
I n this Article
Returns a Boolean value that indicates whether the specified prefix is contained in the collection.

public bool Contains (string uriPrefix);


abstract member Contains : string -> bool
override this.Contains : string -> bool

Parameters
uriPrefix String String
A String that contains the Uniform Resource Identifier (URI) prefix to test.
Returns
Boolean Boolean
true if this collection contains the prefix specified by uriPrefix ; otherwise, false .
Exceptions
ArgumentNullException ArgumentNullException
uriPrefix is null .

Examples
The following code example checks to see whether a user-specified prefix is contained in the prefix collection of an
HttpListener.
public static bool CheckForPrefix(HttpListener listener, string prefix)
{
// Get the prefixes that the Web server is listening to.
HttpListenerPrefixCollection prefixes = listener.Prefixes;
if (prefixes.Count == 0 || prefix == null)
{
return false;
}
return prefixes.Contains(prefix);
}

Remarks
The specified prefix must exactly match an existing value.
HttpListenerPrefixCollection.CopyTo HttpListenerPrefix
Collection.CopyTo
I n this Article

Overloads
CopyTo(Array, Int32) CopyTo(Array, Int32)
Copies the contents of an HttpListenerPrefixCollection to the
specified array.

CopyTo(String[], Int32) CopyTo(String[], Int32)


Copies the contents of an HttpListenerPrefixCollection to the
specified string array.

Remarks
The array must be able to contain strings and cannot be multidimensional.

CopyTo(Array, Int32) CopyTo(Array, Int32)


Copies the contents of an HttpListenerPrefixCollection to the specified array.
public void CopyTo (Array array, int offset);
member this.CopyTo : Array * int -> unit

Parameters
array Array Array
The one dimensional Array that receives the Uniform Resource Identifier (URI) prefix strings in this collection.
offset Int32 Int32
The zero-based index in array at which copying begins.
Exceptions
ArgumentException ArgumentException
array has more than one dimension.

ArgumentOutOfRangeException ArgumentOutOfRangeException
This collection contains more elements than can be stored in array starting at offset .
ObjectDisposedException ObjectDisposedException
The HttpListener associated with this collection is closed.
InvalidCastException InvalidCastException
array cannot store string values.
Examples
The following code example copies the prefixes in a HttpListenerPrefixCollection.
public static string[] CopyPrefixes (HttpListener listener)
{
HttpListenerPrefixCollection prefixes = listener.Prefixes;
string[] prefixArray = new string[prefixes.Count];
prefixes.CopyTo(prefixArray, 0);
return prefixArray;
}

Remarks
The array must be able to contain strings and cannot be multidimensional.

CopyTo(String[], Int32) CopyTo(String[], Int32)


Copies the contents of an HttpListenerPrefixCollection to the specified string array.
public void CopyTo (string[] array, int offset);
abstract member CopyTo : string[] * int -> unit
override this.CopyTo : string[] * int -> unit

Parameters
array String[]
The one dimensional string array that receives the Uniform Resource Identifier (URI) prefix strings in this collection.
offset Int32 Int32
The zero-based index in array at which copying begins.
Exceptions
ArgumentException ArgumentException
array has more than one dimension.

ArgumentOutOfRangeException ArgumentOutOfRangeException
This collection contains more elements than can be stored in array starting at offset .

ObjectDisposedException ObjectDisposedException
The HttpListener associated with this collection is closed.
Examples
The following code example copies the prefixes in a HttpListenerPrefixCollection.
public static string[] CopyPrefixes (HttpListener listener)
{
HttpListenerPrefixCollection prefixes = listener.Prefixes;
string[] prefixArray = new string[prefixes.Count];
prefixes.CopyTo(prefixArray, 0);
return prefixArray;
}

Remarks
The array must be able to contain strings and cannot be multidimensional.
HttpListenerPrefixCollection.Count HttpListenerPrefix
Collection.Count
I n this Article
Gets the number of prefixes contained in the collection.

public int Count { get; }


member this.Count : int

Returns
Int32 Int32
An Int32 that contains the number of prefixes in this collection.

Examples
The following code example displays the prefixes in a collection.
public static void DisplayPrefixesAndState(HttpListener listener)
{
// List the prefixes to which the server listens.
HttpListenerPrefixCollection prefixes = listener.Prefixes;
if (prefixes.Count == 0)
{
Console.WriteLine("There are no prefixes.");
}
foreach(string prefix in prefixes)
{
Console.WriteLine(prefix);
}
// Show the listening state.
if (listener.IsListening)
{
Console.WriteLine("The server is listening.");
}
}
HttpListenerPrefixCollection.GetEnumerator HttpListener
PrefixCollection.GetEnumerator
I n this Article
Returns an object that can be used to iterate through the collection.

public System.Collections.Generic.IEnumerator<string> GetEnumerator ();


abstract member GetEnumerator : unit -> System.Collections.Generic.IEnumerator<string>
override this.GetEnumerator : unit -> System.Collections.Generic.IEnumerator<string>

Returns
IEnumerator<String>
An object that implements the IEnumerator interface and provides access to the strings in this collection.

Examples
The following code example demonstrates enumerating through a collection. Note that the Visual Basic and C#
examples use language specific statements to enumerate through the collection instead of retrieving the enumerator.
public static void DisplayPrefixesAndState(HttpListener listener)
{
// List the prefixes to which the server listens.
HttpListenerPrefixCollection prefixes = listener.Prefixes;
if (prefixes.Count == 0)
{
Console.WriteLine("There are no prefixes.");
}
foreach(string prefix in prefixes)
{
Console.WriteLine(prefix);
}
// Show the listening state.
if (listener.IsListening)
{
Console.WriteLine("The server is listening.");
}
}

Remarks
The object that is returned by this method is initially positioned before the first element in this collection. You must call
the MoveNext method before you can access the first element. To access the element at the current position, call the
Current property.
Do not modify the collection while using the enumerator. If the collection is modified while an enumerator is in use, an
attempt to set the position by calling MoveNext or Reset causes an InvalidOperationException.
For a detailed description of enumerators, see the documentation for the IEnumerator class and the GetEnumerator
method.
HttpListenerPrefixCollection.IEnumerable.GetEnumerator
I n this Article
Returns an object that can be used to iterate through the collection.
System.Collections.IEnumerator IEnumerable.GetEnumerator ();

Returns
IEnumerator
An object that implements the IEnumerator interface and provides access to the strings in this collection.

Remarks
The object that is returned by this method is initially positioned before the first element in this collection. You must call
the MoveNext method before you can access the first element. To access the element at the current position, call the
Current property.
Do not modify the collection while using the enumerator. If the collection is modified while an enumerator is in use, an
attempt to set the position by calling MoveNext or Reset causes an InvalidOperationException.
For a detailed description of enumerators, see the documentation for the IEnumerator class and the GetEnumerator
method.
HttpListenerPrefixCollection.IsReadOnly HttpListener
PrefixCollection.IsReadOnly
I n this Article
Gets a value that indicates whether access to the collection is read-only.

public bool IsReadOnly { get; }


member this.IsReadOnly : bool

Returns
Boolean Boolean
Always returns false .
HttpListenerPrefixCollection.IsSynchronized HttpListener
PrefixCollection.IsSynchronized
I n this Article
Gets a value that indicates whether access to the collection is synchronized (thread-safe).

public bool IsSynchronized { get; }


member this.IsSynchronized : bool

Returns
Boolean Boolean
This property always returns false .

Remarks
Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized,
other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread
safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions that
result from changes made by other threads.
HttpListenerPrefixCollection.Remove HttpListenerPrefix
Collection.Remove
I n this Article
Removes the specified Uniform Resource Identifier (URI) from the list of prefixes handled by the HttpListener object.

public bool Remove (string uriPrefix);


abstract member Remove : string -> bool
override this.Remove : string -> bool

Parameters
uriPrefix String String
A String that contains the URI prefix to remove.
Returns
Boolean Boolean
true if the uriPrefix was found in the HttpListenerPrefixCollection and removed; otherwise false .
Exceptions
ArgumentNullException ArgumentNullException
uriPrefix is null .
HttpListenerException HttpListenerException
A Windows function call failed. To determine the cause of the exception, check the exception's error code.
ObjectDisposedException ObjectDisposedException
The HttpListener associated with this collection is closed.

Remarks
If uriPrefix is not in the collection, this method does nothing.
HttpListenerRequest HttpListenerRequest Class
Describes an incoming HTTP request to an HttpListener object. This class cannot be inherited.

D eclaration
public sealed class HttpListenerRequest
type HttpListenerRequest = class

I nheritance H ierarchy
Object Object

Remarks
When a client makes a request to a Uniform Resource Identifier (URI) handled by an HttpListener object, the
HttpListener provides a HttpListenerContext object that contains information about the sender, the request, and the
response that is sent to the client. The HttpListenerContext.Request property returns the HttpListenerRequest object
that describes the request.
The HttpListenerRequest object contains information about the request, such as the request HttpMethod string,
UserAgent string, and request body data (see the InputStream property).
To reply to the request, you must get the associated response using the Response property.

Properties
AcceptTypes
AcceptTypes

Gets the MIME types accepted by the client.

ClientCertificateError
ClientCertificateError

Gets an error code that identifies a problem with the X509Certificate provided by the client.

ContentEncoding
ContentEncoding

Gets the content encoding that can be used with data sent with the request

ContentLength64
ContentLength64

Gets the length of the body data included in the request.

ContentType
ContentType
Gets the MIME type of the body data included in the request.

Cookies
Cookies

Gets the cookies sent with the request.

HasEntityBody
HasEntityBody

Gets a Boolean value that indicates whether the request has associated body data.

Headers
Headers

Gets the collection of header name/value pairs sent in the request.

HttpMethod
HttpMethod

Gets the HTTP method specified by the client.

InputStream
InputStream

Gets a stream that contains the body data sent by the client.

IsAuthenticated
IsAuthenticated

Gets a Boolean value that indicates whether the client sending this request is authenticated.

IsLocal
IsLocal

Gets a Boolean value that indicates whether the request is sent from the local computer.

IsSecureConnection
IsSecureConnection

Gets a Boolean value that indicates whether the TCP connection used to send the request is using the Secure
Sockets Layer (SSL ) protocol.
IsWebSocketRequest
IsWebSocketRequest

Gets a Boolean value that indicates whether the TCP connection was a WebSocket request.

KeepAlive
KeepAlive

Gets a Boolean value that indicates whether the client requests a persistent connection.

LocalEndPoint
LocalEndPoint

Gets the server IP address and port number to which the request is directed.

ProtocolVersion
ProtocolVersion

Gets the HTTP version used by the requesting client.

QueryString
QueryString

Gets the query string included in the request.

RawUrl
RawUrl

Gets the URL information (without the host and port) requested by the client.

RemoteEndPoint
RemoteEndPoint

Gets the client IP address and port number from which the request originated.

RequestTraceIdentifier
RequestTraceIdentifier

Gets the request identifier of the incoming HTTP request.

ServiceName
ServiceName

Gets the Service Provider Name (SPN ) that the client sent on the request.
TransportContext
TransportContext

Gets the TransportContext for the client request.

Url
Url

Gets the Uri object requested by the client.

UrlReferrer
UrlReferrer

Gets the Uniform Resource Identifier (URI) of the resource that referred the client to the server.

UserAgent
UserAgent

Gets the user agent presented by the client.

UserHostAddress
UserHostAddress

Gets the server IP address and port number to which the request is directed.

UserHostName
UserHostName

Gets the DNS name and, if provided, the port number specified by the client.

UserLanguages
UserLanguages

Gets the natural languages that are preferred for the response.

Methods
BeginGetClientCertificate(AsyncCallback, Object)
BeginGetClientCertificate(AsyncCallback, Object)

Begins an asynchronous request for the client's X.509 v.3 certificate.

EndGetClientCertificate(IAsyncResult)
EndGetClientCertificate(IAsyncResult)

Ends an asynchronous request for the client's X.509 v.3 certificate.


GetClientCertificate()
GetClientCertificate()

Retrieves the client's X.509 v.3 certificate.

GetClientCertificateAsync()
GetClientCertificateAsync()

Retrieves the client's X.509 v.3 certificate as an asynchronous operation.


HttpListenerRequest.AcceptTypes HttpListenerRequest.
AcceptTypes
I n this Article
Gets the MIME types accepted by the client.

public string[] AcceptTypes { get; }


member this.AcceptTypes : string[]

Returns
String[]
A String array that contains the type names specified in the request's Accept header or null if the client request did
not include an Accept header.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}
Remarks
The Accept header is a string of space-separated Multipurpose Internet Mail Extensions (MIME ) type names (for
example, image/jpeg ), which indicate the MIME types that the client is prepared to accept and process in a response.
The */* entry indicates that the client accepts any MIME type. For a detailed description of the Accept header, see
RFC 2616, available at https://www.rfc-editor.org.
For a complete list of request headers, see the HttpRequestHeader enumeration.
HttpListenerRequest.BeginGetClientCertificate Http
ListenerRequest.BeginGetClientCertificate
I n this Article
Begins an asynchronous request for the client's X.509 v.3 certificate.

public IAsyncResult BeginGetClientCertificate (AsyncCallback requestCallback, object state);


member this.BeginGetClientCertificate : AsyncCallback * obj -> IAsyncResult

Parameters
requestCallback AsyncCallback AsyncCallback
An AsyncCallback delegate that references the method to invoke when the operation is complete.
state Object Object
A user-defined object that contains information about the operation. This object is passed to the callback delegate
when the operation completes.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that indicates the status of the operation.
HttpListenerRequest.ClientCertificateError HttpListener
Request.ClientCertificateError
I n this Article
Gets an error code that identifies a problem with the X509Certificate provided by the client.

public int ClientCertificateError { get; }


member this.ClientCertificateError : int

Returns
Int32 Int32
An Int32 value that contains a Windows error code.
Exceptions
InvalidOperationException InvalidOperationException
The client certificate has not been initialized yet by a call to the BeginGetClientCertificate(AsyncCallback, Object) or
GetClientCertificate() methods
-or -
The operation is still in progress.

Examples
The following code example checks this property to determine whether the request includes a valid client certificate.
Console.WriteLine("Listening for {0} prefixes...", listener.Prefixes.Count);
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
Console.WriteLine("Received a request.");
// This server requires a valid client certificate
// for requests that are not sent from the local computer.

// Did the client omit the certificate or send an invalid certificate?


if (request.IsAuthenticated &&
request.GetClientCertificate() == null ||
request.ClientCertificateError != 0)
{
// Send a 403 response.
HttpListenerResponse badCertificateResponse = context.Response ;
SendBadCertificateResponse(badCertificateResponse);
Console.WriteLine("Client has invalid certificate.");
continue;
}

Remarks
This property contains a Windows error code returned by the Secure Channel (Schannel) Security Support Provider
Interface (SSPI), which is used to validate the certificate. For more information about SSPI support for Schannel, see
"Creating a Secure Connection Using Schannel" in the Security documentation at http://msdn.microsoft.com/library.
HttpListenerRequest.ContentEncoding HttpListener
Request.ContentEncoding
I n this Article
Gets the content encoding that can be used with data sent with the request

public System.Text.Encoding ContentEncoding { get; }


member this.ContentEncoding : System.Text.Encoding

Returns
Encoding Encoding
An Encoding object suitable for use with the data in the InputStream property.

Examples
The following code example demonstrates using the ContentEncoding property.
public static void ShowRequestData (HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Console.WriteLine("No client data was sent with the request.");
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (request.ContentType != null)
{
Console.WriteLine("Client data content type {0}", request.ContentType);
}
Console.WriteLine("Client data content length {0}", request.ContentLength64);

Console.WriteLine("Start of client data:");


// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
Console.WriteLine(s);
Console.WriteLine("End of client data:");
body.Close();
reader.Close();
// If you are finished with the request, it should be closed also.
}

Remarks
An Encoding object can be used to convert byte sequences into character sets (code pages) and characters into byte
sequences. This property uses the charset value from the Content-Type header to determine the encoding. If that
information is not available, this property returns Encoding.Default.
HttpListenerRequest.ContentLength64 HttpListener
Request.ContentLength64
I n this Article
Gets the length of the body data included in the request.

public long ContentLength64 { get; }


member this.ContentLength64 : int64

Returns
Int64 Int64
The value from the request's Content-Length header. This value is -1 if the content length is not known.

Examples
The following code example uses the ContentLength64 property while processing body data.
public static void ShowRequestData (HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Console.WriteLine("No client data was sent with the request.");
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (request.ContentType != null)
{
Console.WriteLine("Client data content type {0}", request.ContentType);
}
Console.WriteLine("Client data content length {0}", request.ContentLength64);

Console.WriteLine("Start of client data:");


// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
Console.WriteLine(s);
Console.WriteLine("End of client data:");
body.Close();
reader.Close();
// If you are finished with the request, it should be closed also.
}

Remarks
The Content-Length header expresses the length, in bytes, of the body data that accompanies the request.
For a complete list of request headers, see the HttpRequestHeader enumeration.
HttpListenerRequest.ContentType HttpListenerRequest.
ContentType
I n this Article
Gets the MIME type of the body data included in the request.

public string ContentType { get; }


member this.ContentType : string

Returns
String String
A String that contains the text of the request's Content-Type header.

Examples
The following code example demonstrates how to use this property.
public static void ShowRequestData (HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Console.WriteLine("No client data was sent with the request.");
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (request.ContentType != null)
{
Console.WriteLine("Client data content type {0}", request.ContentType);
}
Console.WriteLine("Client data content length {0}", request.ContentLength64);

Console.WriteLine("Start of client data:");


// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
Console.WriteLine(s);
Console.WriteLine("End of client data:");
body.Close();
reader.Close();
// If you are finished with the request, it should be closed also.
}

Remarks
If a client includes body data in a request, it declares the Multipurpose Internet Mail Extensions (MIME ) type of the
body data in the Content-Type header. For example, the default MIME type of data returned from a Web form using
the POST method is application/x-www-form-urlencoded .
For a complete list of request headers, see the HttpRequestHeader enumeration and RFC 2616, available at
https://www.rfc-editor.org.
The ContentType is null when there is no Content-Type header in the request.
HttpListenerRequest.Cookies HttpListenerRequest.
Cookies
I n this Article
Gets the cookies sent with the request.

public System.Net.CookieCollection Cookies { get; }


member this.Cookies : System.Net.CookieCollection

Returns
CookieCollection CookieCollection
A CookieCollection that contains cookies that accompany the request. This property returns an empty collection if the
request does not contain cookies.

Examples
The following code example displays the values of cookies sent with the request.
// This example requires the System and System.Net nam'espaces.
public static void DisplayCookies(HttpListenerRequest request)
{
// Print the properties of each cookie.
foreach (Cookie cook in request.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}
}

Remarks
A cookie is name/value text data from a Web server that is stored on the local (client) computer.
HttpListenerRequest.EndGetClientCertificate Http
ListenerRequest.EndGetClientCertificate
I n this Article
Ends an asynchronous request for the client's X.509 v.3 certificate.

public System.Security.Cryptography.X509Certificates.X509Certificate2 EndGetClientCertificate


(IAsyncResult asyncResult);
member this.EndGetClientCertificate : IAsyncResult ->
System.Security.Cryptography.X509Certificates.X509Certificate2

Parameters
asyncResult IAsyncResult IAsyncResult
The pending request for the certificate.
Returns
X509Certificate2 X509Certificate2
The IAsyncResult object that is returned when the operation started.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .
ArgumentException ArgumentException
asyncResult was not obtained by calling BeginGetClientCertificate(AsyncCallback, Object) e.
InvalidOperationException InvalidOperationException
This method was already called for the operation identified by asyncResult .
HttpListenerRequest.GetClientCertificate HttpListener
Request.GetClientCertificate
I n this Article
Retrieves the client's X.509 v.3 certificate.

public System.Security.Cryptography.X509Certificates.X509Certificate2 GetClientCertificate ();


member this.GetClientCertificate : unit ->
System.Security.Cryptography.X509Certificates.X509Certificate2

Returns
X509Certificate2 X509Certificate2
A System.Security.Cryptography.X509Certificates object that contains the client's X.509 v.3 certificate.
Exceptions
InvalidOperationException InvalidOperationException
A call to this method to retrieve the client's X.509 v.3 certificate is in progress and therefore another call to this method
cannot be made.

Remarks
This method blocks until the certificate is retrieved.
HttpListenerRequest.GetClientCertificateAsync Http
ListenerRequest.GetClientCertificateAsync
I n this Article
Retrieves the client's X.509 v.3 certificate as an asynchronous operation.

public System.Threading.Tasks.Task<System.Security.Cryptography.X509Certificates.X509Certificate2>
GetClientCertificateAsync ();
member this.GetClientCertificateAsync : unit ->
System.Threading.Tasks.Task<System.Security.Cryptography.X509Certificates.X509Certificate2>

Returns
Task<X509Certificate2>
The task object representing the asynchronous operation. The Result property on the task object returns a
System.Security.Cryptography.X509Certificates object that contains the client's X.509 v.3 certificate.

Remarks
This operation will not block. The returned Task<TResult> object will complete when the certificate has been retrieved.
If a call to this method to retrieve the client's X.509 v.3 certificate is in progress, then another call to this method cannot
be made.
HttpListenerRequest.HasEntityBody HttpListenerRequest.
HasEntityBody
I n this Article
Gets a Boolean value that indicates whether the request has associated body data.

public bool HasEntityBody { get; }


member this.HasEntityBody : bool

Returns
Boolean Boolean
true if the request has associated body data; otherwise, false .

Examples
The following code example demonstrates using this property.
public static void ShowRequestData (HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Console.WriteLine("No client data was sent with the request.");
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (request.ContentType != null)
{
Console.WriteLine("Client data content type {0}", request.ContentType);
}
Console.WriteLine("Client data content length {0}", request.ContentLength64);

Console.WriteLine("Start of client data:");


// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
Console.WriteLine(s);
Console.WriteLine("End of client data:");
body.Close();
reader.Close();
// If you are finished with the request, it should be closed also.
}

Remarks
A request that sends data to the server using the POST method, for example, should have an entity body.
HttpListenerRequest.Headers HttpListenerRequest.
Headers
I n this Article
Gets the collection of header name/value pairs sent in the request.

public System.Collections.Specialized.NameValueCollection Headers { get; }


member this.Headers : System.Collections.Specialized.NameValueCollection

Returns
NameValueCollection NameValueCollection
A WebHeaderCollection that contains the HTTP headers included in the request.

Examples
The following code example displays all the information in a given WebHeaderCollection object.
// Displays the header information that accompanied a request.
public static void DisplayWebHeaderCollection(HttpListenerRequest request)
{
System.Collections.Specialized.NameValueCollection headers = request.Headers;
// Get each header and display each value.
foreach (string key in headers.AllKeys)
{
string[] values = headers.GetValues(key);
if(values.Length > 0)
{
Console.WriteLine("The values of the {0} header are: ", key);
foreach (string value in values)
{
Console.WriteLine(" {0}", value);
}
}
else
Console.WriteLine("There is no value associated with the header.");
}
}

Remarks
Request headers contain metadata information. For example, headers can contain the Uniform Resource Identifier
(URI) of the resource that referred the client to the server, the identity of the user agent employed by the client, and the
acceptable MIME types for data in the response body.
For a complete list of request headers, see the HttpRequestHeader enumeration.
HttpListenerRequest.HttpMethod HttpListenerRequest.
HttpMethod
I n this Article
Gets the HTTP method specified by the client.

public string HttpMethod { get; }


member this.HttpMethod : string

Returns
String String
A String that contains the method used in the request.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
The HTTP method is typically GET or POST, depending on the action desired by the client.
HttpListenerRequest.InputStream HttpListenerRequest.
InputStream
I n this Article
Gets a stream that contains the body data sent by the client.

public System.IO.Stream InputStream { get; }


member this.InputStream : System.IO.Stream

Returns
Stream Stream
A readable Stream object that contains the bytes sent by the client in the body of the request. This property returns
Null if no data is sent with the request.

Examples
The following code example demonstrates using this property to read the data sent with a request.
public static void ShowRequestData (HttpListenerRequest request)
{
if (!request.HasEntityBody)
{
Console.WriteLine("No client data was sent with the request.");
return;
}
System.IO.Stream body = request.InputStream;
System.Text.Encoding encoding = request.ContentEncoding;
System.IO.StreamReader reader = new System.IO.StreamReader(body, encoding);
if (request.ContentType != null)
{
Console.WriteLine("Client data content type {0}", request.ContentType);
}
Console.WriteLine("Client data content length {0}", request.ContentLength64);

Console.WriteLine("Start of client data:");


// Convert the data to a string and display it on the console.
string s = reader.ReadToEnd();
Console.WriteLine(s);
Console.WriteLine("End of client data:");
body.Close();
reader.Close();
// If you are finished with the request, it should be closed also.
}

Remarks
If the client transmits data (for example, using the HTTP POST method), the stream returned by this method contains
that data.
Note

Closing the request does not close the stream returned by this property. When you no longer need the stream, you
should close it by calling the Close method.
HttpListenerRequest.IsAuthenticated HttpListener
Request.IsAuthenticated
I n this Article
Gets a Boolean value that indicates whether the client sending this request is authenticated.

public bool IsAuthenticated { get; }


member this.IsAuthenticated : bool

Returns
Boolean Boolean
true if the client was authenticated; otherwise, false .

Examples
The following code example displays the value of the IsAuthenticated property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
Your application requests client authentication using the AuthenticationSchemes or
AuthenticationSchemeSelectorDelegate property.
Your application does not receive an HttpListenerContext for requests from clients that are not successfully
authenticated.
HttpListenerRequest.IsLocal HttpListenerRequest.IsLocal
I n this Article
Gets a Boolean value that indicates whether the request is sent from the local computer.
public bool IsLocal { get; }
member this.IsLocal : bool

Returns
Boolean Boolean
true if the request originated on the same computer as the HttpListener object that provided the request; otherwise,
false .

Examples
The following code example demonstrates using the IsLocal property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
Applications can use this property to perform special processing when requests are from the local computer.
HttpListenerRequest.IsSecureConnection HttpListener
Request.IsSecureConnection
I n this Article
Gets a Boolean value that indicates whether the TCP connection used to send the request is using the Secure Sockets
Layer (SSL ) protocol.
public bool IsSecureConnection { get; }
member this.IsSecureConnection : bool

Returns
Boolean Boolean
true if the TCP connection is using SSL; otherwise, false .

Examples
The following code example demonstrates using the IsSecureConnection property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
To request a secure connection, the client request uses UriSchemeHttps instead of UriSchemeHttp. If the connection
cannot be established using SSL, the client receives a WebException that provides information about the error.
HttpListenerRequest.IsWebSocketRequest HttpListener
Request.IsWebSocketRequest
I n this Article
Gets a Boolean value that indicates whether the TCP connection was a WebSocket request.

public bool IsWebSocketRequest { get; }


member this.IsWebSocketRequest : bool

Returns
Boolean Boolean
Returns Boolean.
true if the TCP connection is a WebSocket request; otherwise, false .
HttpListenerRequest.KeepAlive HttpListenerRequest.
KeepAlive
I n this Article
Gets a Boolean value that indicates whether the client requests a persistent connection.

public bool KeepAlive { get; }


member this.KeepAlive : bool

Returns
Boolean Boolean
true if the connection should be kept open; otherwise, false .

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
If an HTTP client and server expect to exchange data multiple times in a short time period, a persistent connection
speeds up their communications by allowing them to avoid the overhead required to open and close a TCP connection
for each message. For clients using HTTP/1.1, the default value for this property is true .
HttpListenerRequest.LocalEndPoint HttpListenerRequest.
LocalEndPoint
I n this Article
Gets the server IP address and port number to which the request is directed.

public System.Net.IPEndPoint LocalEndPoint { get; }


member this.LocalEndPoint : System.Net.IPEndPoint

Returns
IPEndPoint IPEndPoint
An IPEndPoint that represents the IP address that the request is sent to.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
This property is useful when you want to respond to requests based on the way they are addressed.
HttpListenerRequest.ProtocolVersion HttpListener
Request.ProtocolVersion
I n this Article
Gets the HTTP version used by the requesting client.

public Version ProtocolVersion { get; }


member this.ProtocolVersion : Version

Returns
Version Version
A Version that identifies the client's version of HTTP.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

Remarks
The capabilities of different HTTP versions are specified in the documents available at https://www.rfc-editor.org.
HttpListenerRequest.QueryString HttpListenerRequest.
QueryString
I n this Article
Gets the query string included in the request.

public System.Collections.Specialized.NameValueCollection QueryString { get; }


member this.QueryString : System.Collections.Specialized.NameValueCollection

Returns
NameValueCollection NameValueCollection
A NameValueCollection object that contains the query data included in the request Url.

Examples
The following code example demonstrates using the QueryString property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}

Remarks
In a URL, the query information is separated from the path information by a question mark (?). Name/value pairs are
separated by an equals sign (=). To access the query data as a single string, get the Query property value from the Uri
object returned by Url.
Note

Queries without an equal sign (example: http://www.contoso.com/query.htm?Name ) are added to the null key in the
NameValueCollection.
HttpListenerRequest.RawUrl HttpListenerRequest.RawUrl
I n this Article
Gets the URL information (without the host and port) requested by the client.
public string RawUrl { get; }
member this.RawUrl : string

Returns
String String
A String that contains the raw URL for this request.

Examples
The following code example demonstrates using the RawUrl property.
public static void CheckTestUrl(HttpListener listener, HttpListenerRequest request)
{
if (request.RawUrl == "/www.contoso.com/test/NoReply")
{
listener.Abort ();
return;
}

Remarks
The raw URL is defined as the part of the URL following the domain information. In the URL string
http://www.contoso.com/articles/recent.aspx , the raw URL is /articles/recent.aspx . The raw URL includes the
query string, if present.
To obtain the host and port information, use the RemoteEndPoint property.
HttpListenerRequest.RemoteEndPoint HttpListener
Request.RemoteEndPoint
I n this Article
Gets the client IP address and port number from which the request originated.

public System.Net.IPEndPoint RemoteEndPoint { get; }


member this.RemoteEndPoint : System.Net.IPEndPoint

Returns
IPEndPoint IPEndPoint
An IPEndPoint that represents the IP address and port number from which the request originated.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties2 (HttpListenerRequest request)
{
Console.WriteLine("KeepAlive: {0}", request.KeepAlive);
Console.WriteLine("Local end point: {0}", request.LocalEndPoint.ToString());
Console.WriteLine("Remote end point: {0}", request.RemoteEndPoint.ToString());
Console.WriteLine("Is local? {0}", request.IsLocal);
Console.WriteLine("HTTP method: {0}", request.HttpMethod);
Console.WriteLine("Protocol version: {0}", request.ProtocolVersion);
Console.WriteLine("Is authenticated: {0}", request.IsAuthenticated);
Console.WriteLine("Is secure: {0}", request.IsSecureConnection);

}
HttpListenerRequest.RequestTraceIdentifier HttpListener
Request.RequestTraceIdentifier
I n this Article
Gets the request identifier of the incoming HTTP request.

public Guid RequestTraceIdentifier { get; }


member this.RequestTraceIdentifier : Guid

Returns
Guid Guid
A Guid object that contains the identifier of the HTTP request.
HttpListenerRequest.ServiceName HttpListenerRequest.
ServiceName
I n this Article
Gets the Service Provider Name (SPN ) that the client sent on the request.

public string ServiceName { get; }


member this.ServiceName : string

Returns
String String
A String that contains the SPN the client sent on the request.

Remarks
An application could use the ServiceName property to perform custom Service Provide Name (SPN ) validation.
See TransportContextTransportContext
Also Integrated Windows Authentication with Extended Protection
HttpListenerRequest.TransportContext HttpListener
Request.TransportContext
I n this Article
Gets the TransportContext for the client request.

public System.Net.TransportContext TransportContext { get; }


member this.TransportContext : System.Net.TransportContext

Returns
TransportContext TransportContext
A TransportContext object for the client request.

Remarks
The TransportContext property can be used to retrieve the channel binding token (CBT) for an HttpListenerRequest
which was sent using HTTPS.
An application could use the TransportContext property to perform custom authentication using calls to the native
Win32 AcceptSecurityContext function.
If an application attempts to retrieve the channel binding token (CBT) from this TransportContext property using the
GetChannelBinding method and the ChannelBindingKind is not Endpoint, then the HttpListenerRequest will throw
NotSupportedException. The HttpListenerRequest overrides the GetChannelBinding method with an internal
implementation.
See ServiceNameServiceName
Also Integrated Windows Authentication with Extended Protection
HttpListenerRequest.Url HttpListenerRequest.Url
I n this Article
Gets the Uri object requested by the client.
public Uri Url { get; }
member this.Url : Uri

Returns
Uri Uri
A Uri object that identifies the resource requested by the client.

Examples
The following code example demonstrates using the Url property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}

Remarks
The Url property allows you to obtain all the information available from a Uri object. If you need to know only the raw
text of the URI request, consider using the RawUrl property instead.
The Url property is null if the Uri from the client could not be parsed.
The UnescapeRequestUrl property indicates if HttpListener uses the raw unescaped URI instead of the converted URI
where any percent-encoded values are converted and other normalization steps are taken.
When a HttpListener instance receives a request through the http.sys service, it creates an instance of the URI string
provided by http.sys , and exposes it as the HttpListenerRequest.Url property.
The http.sys service exposes two request URI strings:
Raw URI
Converted URI
The raw URI is the System.Uri provided in the request line of a HTTP request:
GET /path/

Host: www.contoso.com

The raw URI provided by http.sys for the request mentioned above, is "/path/". This represents the string following
the HTTP verb as it was sent over the network.
The http.sys service creates a converted URI from the information provided in the request using the URI provided in
the HTTP request line and the Host header to determine the origin server the request should be forwarded to. This is
done by comparing the information from the request with a set of registered URI prefixes. In order to be able to
compare those values, some normalization to the request needs to be done. For the sample above the converted URI
would be as follows:
http://www.contoso.com/path/

The http.sys service combines the Uri.Host property value and the string in the request line to create a converted
URI. In addition, http.sys and the System.Uri class also do the following:
Un-escapes all percent encoded values.
Converts percent-encoded non-ASCII characters into a UTF -16 character representation. Note that UTF -8 and
ANSI/DBCS characters are supported as well as Unicode characters (Unicode encoding using the %uXXXX format).
Executes other normalization steps, like path compression.
Since the request doesn't contain any information about the encoding used for percent-encoded values, it may not be
possible to determine the correct encoding just by parsing the percent-encoded values.
Therefore http.sys provides two registry keys for modifying the process:

R EG IS TR Y K EY D EFAU LT V ALU E D ES CR IPTIO N

EnableNonUTF8 1 If zero, http.sys accepts only UTF-8-


encoded URLs.

If non-zero, http.sys also accepts


ANSI-encoded or DBCS-encoded URLs
in requests.
R EG IS TR Y K EY D EFAU LT V ALU E D ES CR IPTIO N

FavorUTF8 1 If non-zero, http.sys always tries to


decode a URL as UTF-8 first; if that
conversion fails and EnableNonUTF8 is
non-zero, Http.sys then tries to decode
it as ANSI or DBCS.

If zero (and EnableNonUTF8 is non-


zero), http.sys tries to decode it as
ANSI or DBCS; if that is not successful, it
tries a UTF-8 conversion.

When HttpListener receives a request, it uses the converted URI from http.sys as input to the Url property.
There is a need for supporting characters besides characters and numbers in URIs. An example is the following URI,
which is used to retrieve customer information for customer number "1/3812":
http://www.contoso.com/Customer('1%2F3812')/

Note the percent-encoded slash in the Uri (%2F ). This is necessary, since in this case the slash character represents data
and not a path delimiter.
Passing the string to Uri constructor will lead to the following URI:
http://www.contoso.com/Customer('1/3812')/

Splitting the path into its segments would result in the following elements:
Customer('1

3812')

This is not the intent of the sender of the request.


If the UnescapeRequestUrl property is set to false, then when the HttpListener receives a request, it uses the raw URI
instead of the converted URI from http.sys as input to the Url property.

See Network Settings Schema


Also <httpListener> Element (Network Settings)
HttpListenerRequest.UrlReferrer HttpListenerRequest.Url
Referrer
I n this Article
Gets the Uniform Resource Identifier (URI) of the resource that referred the client to the server.

public Uri UrlReferrer { get; }


member this.UrlReferrer : Uri

Returns
Uri Uri
A Uri object that contains the text of the request's Referer header, or null if the header was not included in the request.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}

Remarks
If a client has followed a hyperlink to the requested URI, its request might contain a Referrer header that identifies
the URI of the resource that contained the hyperlink.
Clients can falsify or choose not to present a Referer header. Therefore, while the UrlReferrer property can be useful for
identifying basic trends in Web traffic; you should not use it as part of an authorization scheme to control access to
data.
For a complete list of request headers, see the HttpRequestHeader enumeration.
The UrlReferrer is null when there is no Referrer header in the request or when the Referrer header is present in
the request but does not parse to a valid Uri.
HttpListenerRequest.UserAgent HttpListenerRequest.
UserAgent
I n this Article
Gets the user agent presented by the client.

public string UserAgent { get; }


member this.UserAgent : string

Returns
String String
A String object that contains the text of the request's User-Agent header.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}

Remarks
The User-Agent header typically contains text that identifies the name and version number of the software used to
generate the request.
For a complete list of request headers, see the HttpRequestHeader enumeration.
The UserAgent is null when there is no User-Agent header in the request.
HttpListenerRequest.UserHostAddress HttpListener
Request.UserHostAddress
I n this Article
Gets the server IP address and port number to which the request is directed.

public string UserHostAddress { get; }


member this.UserHostAddress : string

Returns
String String
A String that contains the host address information.

Examples
The following code example displays the value of this property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}

Remarks
The information returned by this property is also available in the LocalEndPoint property value.
HttpListenerRequest.UserHostName HttpListener
Request.UserHostName
I n this Article
Gets the DNS name and, if provided, the port number specified by the client.

public string UserHostName { get; }


member this.UserHostName : string

Returns
String String
A String value that contains the text of the request's Host header.

Examples
The following code example demonstrates using this property.
public static void ShowRequestProperties1 (HttpListenerRequest request)
{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}

Remarks
The Host header contains the requested server host name and port number, if specified, separated by a colon (for
example, www.contoso.com:8080 ).
You can use this property to return different responses depending on the host name specified in the request.
For a complete list of request headers, see the HttpRequestHeader enumeration.
HttpListenerRequest.UserLanguages HttpListener
Request.UserLanguages
I n this Article
Gets the natural languages that are preferred for the response.

public string[] UserLanguages { get; }


member this.UserLanguages : string[]

Returns
String[]
A String array that contains the languages specified in the request's AcceptLanguage header or null if the client
request did not include an AcceptLanguage header.

Examples
The following code example displays the languages from the request's Accept-Language header.

public static void ShowRequestProperties1 (HttpListenerRequest request)


{
// Display the MIME types that can be used in the response.
string[] types = request.AcceptTypes;
if (types != null)
{
Console.WriteLine("Acceptable MIME types:");
foreach (string s in types)
{
Console.WriteLine(s);
}
}
// Display the language preferences for the response.
types = request.UserLanguages;
if (types != null)
{
Console.WriteLine("Acceptable natural languages:");
foreach (string l in types)
{
Console.WriteLine(l);
}
}

// Display the URL used by the client.


Console.WriteLine("URL: {0}", request.Url.OriginalString);
Console.WriteLine("Raw URL: {0}", request.RawUrl);
Console.WriteLine("Query: {0}", request.QueryString);

// Display the referring URI.


Console.WriteLine("Referred by: {0}", request.UrlReferrer);

//Display the HTTP method.


Console.WriteLine("HTTP Method: {0}", request.HttpMethod);
//Display the host information specified by the client;
Console.WriteLine("Host name: {0}", request.UserHostName);
Console.WriteLine("Host address: {0}", request.UserHostAddress);
Console.WriteLine("User agent: {0}", request.UserAgent);
}
Remarks
For a detailed description of the Accept-Language header, see RFC 2616 Section 14.4, available at https://www.rfc-
editor.org.
For a complete list of request headers, see the HttpRequestHeader enumeration.
HttpListenerResponse HttpListenerResponse Class
Represents a response to a request being handled by an HttpListener object.

D eclaration
public sealed class HttpListenerResponse : IDisposable
type HttpListenerResponse = class
interface IDisposable

I nheritance H ierarchy
Object Object

Remarks
When a client makes a request for a resource handled by an HttpListener object, the request and response are made
available to your application in an HttpListenerContext object. The request is represented by an HttpListenerRequest
object and is available in the HttpListenerContext.Request property. The response is represented by an
HttpListenerResponse object and is available in the HttpListenerContext.Response property.
You can customize the response by setting various properties, such as StatusCode, StatusDescription, and Cookies. Use
the HttpListenerResponse.OutputStream property to obtain a Stream instance to which response data can be written.
Finally, send the response data to the client by calling the Close method.

Properties
ContentEncoding
ContentEncoding

Gets or sets the Encoding for this response's OutputStream.

ContentLength64
ContentLength64

Gets or sets the number of bytes in the body data included in the response.

ContentType
ContentType

Gets or sets the MIME type of the content returned.

Cookies
Cookies

Gets or sets the collection of cookies returned with the response.

Headers
Headers
Gets or sets the collection of header name/value pairs returned by the server.

KeepAlive
KeepAlive

Gets or sets a value indicating whether the server requests a persistent connection.

OutputStream
OutputStream

Gets a Stream object to which a response can be written.

ProtocolVersion
ProtocolVersion

Gets or sets the HTTP version used for the response.

RedirectLocation
RedirectLocation

Gets or sets the value of the HTTP Location header in this response.

SendChunked
SendChunked

Gets or sets whether the response uses chunked transfer encoding.

StatusCode
StatusCode

Gets or sets the HTTP status code to be returned to the client.

StatusDescription
StatusDescription

Gets or sets a text description of the HTTP status code returned to the client.

Methods
Abort()
Abort()

Closes the connection to the client without sending a response.


AddHeader(String, String)
AddHeader(String, String)

Adds the specified header and value to the HTTP headers for this response.

AppendCookie(Cookie)
AppendCookie(Cookie)

Adds the specified Cookie to the collection of cookies for this response.

AppendHeader(String, String)
AppendHeader(String, String)

Appends a value to the specified HTTP header to be sent with this response.

Close()
Close()

Sends the response to the client and releases the resources held by this HttpListenerResponse instance.

Close(Byte[], Boolean)
Close(Byte[], Boolean)

Returns the specified byte array to the client and releases the resources held by this HttpListenerResponse
instance.

CopyFrom(HttpListenerResponse)
CopyFrom(HttpListenerResponse)

Copies properties from the specified HttpListenerResponse to this response.

Redirect(String)
Redirect(String)

Configures the response to redirect the client to the specified URL.

SetCookie(Cookie)
SetCookie(Cookie)

Adds or updates a Cookie in the collection of cookies sent with this response.

IDisposable.Dispose()
IDisposable.Dispose()

Releases all resources used by the HttpListenerResponse.


HttpListenerResponse.Abort HttpListenerResponse.Abort
I n this Article
Closes the connection to the client without sending a response.
public void Abort ();
member this.Abort : unit -> unit

Remarks
Calling this method on an object that has already been closed has no effect. If the response has not already been
closed, this method closes it and the associated HttpListenerRequest and HttpListenerContext objects. The connection
to the client is also closed, regardless of the KeepAlive property value of the client request.
HttpListenerResponse.AddHeader HttpListenerResponse.
AddHeader
I n this Article
Adds the specified header and value to the HTTP headers for this response.

public void AddHeader (string name, string value);


member this.AddHeader : string * string -> unit

Parameters
name String String
The name of the HTTP header to set.
value String String
The value for the name header.

Exceptions
ArgumentNullException ArgumentNullException
name is null or an empty string ("").
ArgumentException ArgumentException
You are not allowed to specify a value for the specified header.
-or-
name or value contains invalid characters.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65,535 characters.

Examples
The following code example demonstrates adding a header using this property.
public static void SetExpirationDate(long seconds, HttpListenerResponse response)
{
response.AddHeader("Expires", seconds.ToString());
}

Remarks
Calling this method is equivalent to calling the Set method on the collection returned by the Headers property.
If the header specified in name does not exist, this method inserts a new header into the Headers property's collection.
If name is present in the collection, this method replaces the existing value with value . To add a value to an existing
header without replacing the existing value, use the AppendHeader method.
See WebHeaderCollectionWebHeaderCollection
Also
HttpListenerResponse.AppendCookie HttpListener
Response.AppendCookie
I n this Article
Adds the specified Cookie to the collection of cookies for this response.

public void AppendCookie (System.Net.Cookie cookie);


member this.AppendCookie : System.Net.Cookie -> unit

Parameters
cookie Cookie Cookie
The Cookie to add to the collection to be sent with this response.
Exceptions
ArgumentNullException ArgumentNullException
cookie is null .

Examples
The following code example demonstrates adding a cookie to a response
// This example requires the System and System.Net namespaces.

public static string NextCustomerID()


{
// A real-world application would do something more robust
// to ensure uniqueness.
return DateTime.Now.ToString();
}
public static void SimpleListenerCookieExample(string[] prefixes)
{
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.IgnoreWriteExceptions = true;
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
string customerID = null;

// Did the request come with a cookie?


Cookie cookie = request.Cookies["ID"];
if (cookie != null)
{
customerID=cookie.Value;
}
if (customerID !=null)
{
Console.WriteLine("Found the cookie!");
}
// Get the response object.
HttpListenerResponse response = context.Response;
// If they didn't provide a cookie containing their ID, give them one.
if (customerID == null)
{
customerID = NextCustomerID();
Cookie cook = new Cookie("ID", customerID );
response.AppendCookie (cook);
}
// Construct a response.
string responseString = "<HTML><BODY> Hello " + customerID + "!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get the response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
// Closing the response sends the response to the client.
response.Close();
listener.Stop();
}

Remarks
Calling this method is equivalent to calling the Add method on the collection returned by the Cookies property.
If the specified cookie does not exist in the Cookies property's collection, cookie is added. If the cookie exists in the
collection, cookie replaces it.
HttpListenerResponse.AppendHeader HttpListener
Response.AppendHeader
I n this Article
Appends a value to the specified HTTP header to be sent with this response.

public void AppendHeader (string name, string value);


member this.AppendHeader : string * string -> unit

Parameters
name String String
The name of the HTTP header to append value to.
value String String
The value to append to the name header.
Exceptions
ArgumentException ArgumentException
name is null or an empty string ("").
-or-
You are not allowed to specify a value for the specified header.
-or-
name or value contains invalid characters.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65,535 characters.

Remarks
Calling this method is equivalent to calling the Add method on the collection returned by the Headers property.
If the header specified in header does not exist, this method inserts a new header into the Headers property's
collection. If header is present in the collection, this method adds value to the existing values. To replace the value of
an existing header, use the AddHeader method.
HttpListenerResponse.Close HttpListenerResponse.Close
I n this Article

Overloads
Close() Close()
Sends the response to the client and releases the resources
held by this HttpListenerResponse instance.

Close(Byte[], Boolean) Close(Byte[], Boolean)


Returns the specified byte array to the client and releases the
resources held by this HttpListenerResponse instance.

Close() Close()
Sends the response to the client and releases the resources held by this HttpListenerResponse instance.
public void Close ();
member this.Close : unit -> unit

Examples
The following code example demonstrates calling this method to send a Forbidden (403) response to the client.
static string message403;
static HttpListenerResponse preMade403Response;
static void SendBadCertificateResponse(HttpListenerResponse response)
{
if (preMade403Response == null)
{
// Set up an authentication error response template.
response.StatusCode = (int)HttpStatusCode.Forbidden;
response.StatusDescription = "403 Forbidden";
response.ProtocolVersion = new Version("1.1");
response.SendChunked = false;

preMade403Response = response;
}
else
{
response.CopyFrom(preMade403Response);
}

// The response body cannot be saved in the template.

StringBuilder message = new StringBuilder();


message.Append("<HTML><BODY>");
message.Append("<p> Error message 403: Access is denied due to a missing or invalid client
certificate.</p>");
message.Append("</BODY></HTML>");
message403 = message.ToString();

// Turn the error message into a byte array using the


// encoding from the response when present.
System.Text.Encoding encoding = response.ContentEncoding;
if (encoding == null)
{
encoding = System.Text.Encoding.UTF8;
response.ContentEncoding = encoding;
}

byte[] buffer = encoding.GetBytes(message403);


response.ContentLength64 = buffer.Length;
// Write the error message.
System.IO.Stream stream = response.OutputStream;
stream.Write(buffer, 0, buffer.Length);
// Send the response.
response.Close();
}

Remarks
This method closes the response stream and the HttpListenerRequest associated with the response.

Close(Byte[], Boolean) Close(Byte[], Boolean)


Returns the specified byte array to the client and releases the resources held by this HttpListenerResponse instance.
public void Close (byte[] responseEntity, bool willBlock);
member this.Close : byte[] * bool -> unit

Parameters
responseEntity Byte[]
A Byte array that contains the response to send to the client.
willBlock Boolean Boolean
true to block execution while flushing the stream to the client; otherwise, false .
Exceptions
ArgumentNullException ArgumentNullException
responseEntity is null .
ObjectDisposedException ObjectDisposedException
This object is closed.
Examples
The following code example demonstrates calling this method.

// This example requires the System and System.Net namespaces.


public static void SimpleListenerExample2(string[] prefixes)
{
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
// Demonstrate using the close overload that takes an
// entity body.
// Specify true to block while data is transmitted.
response.Close(buffer, true);
listener.Stop();
}

Remarks
If you are sending body data with the response, you can use this method to send it as a Byte array instead of writing
the body data to the OutputStream property and calling the Close method.
This method closes the response stream and the HttpListenerRequest associated with the response.
HttpListenerResponse.ContentEncoding HttpListener
Response.ContentEncoding
I n this Article
Gets or sets the Encoding for this response's OutputStream.

public System.Text.Encoding ContentEncoding { get; set; }


member this.ContentEncoding : System.Text.Encoding with get, set

Returns
Encoding Encoding
An Encoding object suitable for use with the data in the OutputStream property, or null if no encoding is specified.

Examples
The following code example demonstrates using this property.
static string message403;
static HttpListenerResponse preMade403Response;
static void SendBadCertificateResponse(HttpListenerResponse response)
{
if (preMade403Response == null)
{
// Set up an authentication error response template.
response.StatusCode = (int)HttpStatusCode.Forbidden;
response.StatusDescription = "403 Forbidden";
response.ProtocolVersion = new Version("1.1");
response.SendChunked = false;

preMade403Response = response;
}
else
{
response.CopyFrom(preMade403Response);
}

// The response body cannot be saved in the template.

StringBuilder message = new StringBuilder();


message.Append("<HTML><BODY>");
message.Append("<p> Error message 403: Access is denied due to a missing or invalid client
certificate.</p>");
message.Append("</BODY></HTML>");
message403 = message.ToString();

// Turn the error message into a byte array using the


// encoding from the response when present.
System.Text.Encoding encoding = response.ContentEncoding;
if (encoding == null)
{
encoding = System.Text.Encoding.UTF8;
response.ContentEncoding = encoding;
}

byte[] buffer = encoding.GetBytes(message403);


response.ContentLength64 = buffer.Length;
// Write the error message.
System.IO.Stream stream = response.OutputStream;
stream.Write(buffer, 0, buffer.Length);
// Send the response.
response.Close();
}

Remarks
An Encoding object can be used to convert byte sequences into character sets (code pages) and characters into byte
sequences.
HttpListenerResponse.ContentLength64 HttpListener
Response.ContentLength64
I n this Article
Gets or sets the number of bytes in the body data included in the response.

public long ContentLength64 { get; set; }


member this.ContentLength64 : int64 with get, set

Returns
Int64 Int64
The value of the response's Content-Length header.

Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for a set operation is less than zero.
InvalidOperationException InvalidOperationException
The response is already being sent.
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates setting the value of this property.
// This example requires the System and System.Net namespaces.
public static void SimpleListenerExample(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
}

Remarks
The Content-Length header expresses the length, in bytes, of the response's body data. When using a format that does
not send the data chunked or raw, you must set the ContentLength64 property. If you do not, the HttpListener does not
send the response data.
For a complete list of response headers, see the HttpResponseHeader enumeration.
HttpListenerResponse.ContentType HttpListener
Response.ContentType
I n this Article
Gets or sets the MIME type of the content returned.

public string ContentType { get; set; }


member this.ContentType : string with get, set

Returns
String String
A String instance that contains the text of the response's Content-Type header.

Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation is null .
ArgumentException ArgumentException
The value specified for a set operation is an empty string ("").
ObjectDisposedException ObjectDisposedException
This object is closed.

Remarks
When communicating with a Web browser, you should explicitly set this property when returning any content type
other than text/html .
For a complete list of response headers, see the HttpResponseHeader enumeration.
HttpListenerResponse.Cookies HttpListenerResponse.
Cookies
I n this Article
Gets or sets the collection of cookies returned with the response.

public System.Net.CookieCollection Cookies { get; set; }


member this.Cookies : System.Net.CookieCollection with get, set

Returns
CookieCollection CookieCollection
A CookieCollection that contains cookies to accompany the response. The collection is empty if no cookies have been
added to the response.

Examples
The following code example checks a request for a cookie, and returns a new cookie with the response if the request
did not have one.
// This example requires the System and System.Net namespaces.

public static string NextCustomerID()


{
// A real-world application would do something more robust
// to ensure uniqueness.
return DateTime.Now.ToString();
}
public static void SimpleListenerCookieExample(string[] prefixes)
{
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.IgnoreWriteExceptions = true;
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
string customerID = null;

// Did the request come with a cookie?


Cookie cookie = request.Cookies["ID"];
if (cookie != null)
{
customerID=cookie.Value;
}
if (customerID !=null)
{
Console.WriteLine("Found the cookie!");
}
// Get the response object.
HttpListenerResponse response = context.Response;
// If they didn't provide a cookie containing their ID, give them one.
if (customerID == null)
{
customerID = NextCustomerID();
Cookie cook = new Cookie("ID", customerID );
response.AppendCookie (cook);
}
// Construct a response.
string responseString = "<HTML><BODY> Hello " + customerID + "!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get the response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
// Closing the response sends the response to the client.
response.Close();
listener.Stop();
}

Remarks
A cookie is name/value text data from a Web server that is stored on the local (client) computer. The following cookie
formats are supported: Netscape, RFC 2109, and RFC 2965. The Netscape cookie specification is available at
http://wp.netscape.com/newsref/std/cookie_spec.html; the RFC documents are available at https://www.rfc-editor.org/.
HttpListenerResponse.CopyFrom HttpListenerResponse.
CopyFrom
I n this Article
Copies properties from the specified HttpListenerResponse to this response.

public void CopyFrom (System.Net.HttpListenerResponse templateResponse);


member this.CopyFrom : System.Net.HttpListenerResponse -> unit

Parameters
templateResponse HttpListenerResponse HttpListenerResponse
The HttpListenerResponse instance to copy.

Examples
The following code example demonstrates creating a response by copying a template response.
static string message403;
static HttpListenerResponse preMade403Response;
static void SendBadCertificateResponse(HttpListenerResponse response)
{
if (preMade403Response == null)
{
// Set up an authentication error response template.
response.StatusCode = (int)HttpStatusCode.Forbidden;
response.StatusDescription = "403 Forbidden";
response.ProtocolVersion = new Version("1.1");
response.SendChunked = false;

preMade403Response = response;
}
else
{
response.CopyFrom(preMade403Response);
}

// The response body cannot be saved in the template.

StringBuilder message = new StringBuilder();


message.Append("<HTML><BODY>");
message.Append("<p> Error message 403: Access is denied due to a missing or invalid client
certificate.</p>");
message.Append("</BODY></HTML>");
message403 = message.ToString();

// Turn the error message into a byte array using the


// encoding from the response when present.
System.Text.Encoding encoding = response.ContentEncoding;
if (encoding == null)
{
encoding = System.Text.Encoding.UTF8;
response.ContentEncoding = encoding;
}

byte[] buffer = encoding.GetBytes(message403);


response.ContentLength64 = buffer.Length;
// Write the error message.
System.IO.Stream stream = response.OutputStream;
stream.Write(buffer, 0, buffer.Length);
// Send the response.
response.Close();
}

Remarks
If you regularly change many properties from their default values to a fixed set of new values, it is convenient to use an
HttpListenerResponse instance as a template. Customize the template response once and, instead of configuring each
response separately, call the CopyFrom method to configure a new response based on property values in the template
response.
The following properties are copied from templateResponse to the current instance.

Headers
ContentLength64
StatusCode
StatusDescription
KeepAlive
ProtocolVersion
HttpListenerResponse.Headers HttpListenerResponse.
Headers
I n this Article
Gets or sets the collection of header name/value pairs returned by the server.

public System.Net.WebHeaderCollection Headers { get; set; }


member this.Headers : System.Net.WebHeaderCollection with get, set

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection instance that contains all the explicitly set HTTP headers to be included in the response.
Exceptions
InvalidOperationException InvalidOperationException
The WebHeaderCollection instance specified for a set operation is not valid for a response.

Examples
The following code example demonstrates displaying the headers in a WebHeaderCollection.
// Displays the header information that accompanied a request.
public static void DisplayWebHeaderCollection(HttpListenerResponse response)
{
WebHeaderCollection headers = response.Headers;
// Get each header and display each value.
foreach (string key in headers.AllKeys)
{
string[] values = headers.GetValues(key);
if(values.Length > 0)
{
Console.WriteLine("The values of the {0} header are: ", key);
foreach (string value in values)
{
Console.WriteLine(" {0}", value);
}
}
else
Console.WriteLine("There is no value associated with the header.");
}
}

Remarks
Response headers contain metadata information such as the date and time of the response, the identity of the
responding server, and the MIME type of the data contained in the response body.
For a complete list of response headers, see the HttpResponseHeader enumeration.
Note

If you attempt to set a Content-Length, Keep-Alive, Transfer-Encoding, or WWW -Authenticate header using the
Headers property, an exception will be thrown. Use the KeepAlive or ContentLength64 properties to set these headers.
You cannot set the Transfer-Encoding or WWW -Authenticate headers manually.
HttpListenerResponse.IDisposable.Dispose
I n this Article
Releases all resources used by the HttpListenerResponse.
void IDisposable.Dispose ();

Remarks
Use the Close method to send the response and release resources held by an HttpListenerResponse. To discard the
response and release the resources held by this instance, use the Abort method.
HttpListenerResponse.KeepAlive HttpListenerResponse.
KeepAlive
I n this Article
Gets or sets a value indicating whether the server requests a persistent connection.

public bool KeepAlive { get; set; }


member this.KeepAlive : bool with get, set

Returns
Boolean Boolean
true if the server requests a persistent connection; otherwise, false . The default is true .

Exceptions
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates setting the value of this property.
// When the client is not authenticated, there is no Identity.
if (context.User == null)
{
message.Append ("<HTML><BODY><p> Hello local user! </p></BODY></HTML>");
}
else
{
// Get the requester's identity.
System.Security.Principal.WindowsIdentity identity = WindowsIdentity.GetCurrent();
// Construct the response body.
message.AppendFormat ("<HTML><BODY><p> Hello {0}!<br/>",
identity.Name);
message.AppendFormat ("You were authenticated using {0}.</p>",
identity.AuthenticationType);
message.Append ("</BODY></HTML>");
}

// Configure the response.


HttpListenerResponse response = context.Response;

// Use the encoding from the response if one has been set.
// Otherwise, use UTF8.
System.Text.Encoding encoding = response.ContentEncoding;
if (encoding == null)
{
encoding = System.Text.Encoding.UTF8;
response.ContentEncoding = encoding;
}
byte[] buffer = encoding.GetBytes (message.ToString ());
response.ContentLength64 = buffer.Length;
response.StatusCode = (int) HttpStatusCode.OK;
response.StatusDescription = "OK";
response.ProtocolVersion = new Version ("1.1");
// Don't keep the TCP connection alive;
// We don't expect multiple requests from the same client.
response.KeepAlive = false;
// Write the response body.
System.IO.Stream stream = response.OutputStream;
stream.Write(buffer, 0, buffer.Length);

Remarks
If an HTTP client and server expect to exchange data multiple times in a short period, a persistent connection speeds
up their communications by allowing them to avoid the overhead required to open and close a TCP connection for
each message. Persistent connections are in widespread use in communications between modern Web browsers and
Web servers.
Persistent connections are described in detail in the HTTP/1.1 protocol specification (RFC 2616) available at the RTF
Editor Web site (https://www.rfc-editor.org/).
HttpListenerResponse.OutputStream HttpListener
Response.OutputStream
I n this Article
Gets a Stream object to which a response can be written.

public System.IO.Stream OutputStream { get; }


member this.OutputStream : System.IO.Stream

Returns
Stream Stream
A Stream object to which a response can be written.
Exceptions
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates calling this method.
// This example requires the System and System.Net namespaces.
public static string ClientInformation(HttpListenerContext context)
{
System.Security.Principal.IPrincipal user = context.User;
System.Security.Principal.IIdentity id = user.Identity;
if (id == null)
{
return "Client authentication is not enabled for this Web server.";
}

string display;
if (id.IsAuthenticated)
{
display = String.Format("{0} was authenticated using {1}", id.Name,
id.AuthenticationType);
}
else
{
display = String.Format("{0} was not authenticated", id.Name);
}
return display;
}

public static void SimpleListenerWithAuthentication(string[] prefixes)


{
if (!HttpListener.IsSupported)
{
Console.WriteLine ("Windows XP SP2 or Server 2003 is required to use the HttpListener
class.");
return;
}

// URI prefixes are required,


// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");

// Set up a listener.
HttpListener listener = new HttpListener();
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
// Specify Negotiate as the authentication scheme.
listener.AuthenticationSchemes = AuthenticationSchemes.Negotiate;
Console.WriteLine("Listening...");
// GetContext blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string clientInformation = ClientInformation(context);
byte[] buffer = System.Text.Encoding.UTF8.GetBytes("<HTML><BODY> " + clientInformation + "
</BODY></HTML>");
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
output.Close();
listener.Stop();
}
Remarks
The ContentLength64 property must be set explicitly before writing to the returned Stream object.
Note

Closing the request does not close the stream returned by this property. When you no longer need the stream, you
should close it by calling the Close method.
HttpListenerResponse.ProtocolVersion HttpListener
Response.ProtocolVersion
I n this Article
Gets or sets the HTTP version used for the response.

public Version ProtocolVersion { get; set; }


member this.ProtocolVersion : Version with get, set

Returns
Version Version
A Version object indicating the version of HTTP used when responding to the client. Note that this property is now
obsolete.
Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation is null .

ArgumentException ArgumentException
The value specified for a set operation does not have its Major property set to 1 or does not have its Minor property
set to either 0 or 1.
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates setting the value of this property.
static string message403;
static HttpListenerResponse preMade403Response;
static void SendBadCertificateResponse(HttpListenerResponse response)
{
if (preMade403Response == null)
{
// Set up an authentication error response template.
response.StatusCode = (int)HttpStatusCode.Forbidden;
response.StatusDescription = "403 Forbidden";
response.ProtocolVersion = new Version("1.1");
response.SendChunked = false;

preMade403Response = response;
}
else
{
response.CopyFrom(preMade403Response);
}

// The response body cannot be saved in the template.

StringBuilder message = new StringBuilder();


message.Append("<HTML><BODY>");
message.Append("<p> Error message 403: Access is denied due to a missing or invalid client
certificate.</p>");
message.Append("</BODY></HTML>");
message403 = message.ToString();

// Turn the error message into a byte array using the


// encoding from the response when present.
System.Text.Encoding encoding = response.ContentEncoding;
if (encoding == null)
{
encoding = System.Text.Encoding.UTF8;
response.ContentEncoding = encoding;
}

byte[] buffer = encoding.GetBytes(message403);


response.ContentLength64 = buffer.Length;
// Write the error message.
System.IO.Stream stream = response.OutputStream;
stream.Write(buffer, 0, buffer.Length);
// Send the response.
response.Close();
}

Remarks
The capabilities of different HTTP versions are specified in the documents available at https://www.ietf.org.
HttpListenerResponse.Redirect HttpListenerResponse.
Redirect
I n this Article
Configures the response to redirect the client to the specified URL.

public void Redirect (string url);


member this.Redirect : string -> unit

Parameters
url String String
The URL that the client should use to locate the requested resource.

Examples
The following code example demonstrates calling this method.

public static void PermanentRedirect(HttpListenerRequest request, HttpListenerResponse response)


{
if (request.Url.OriginalString == @"http://www.contoso.com/index.html")
{
// Sets the location header, status code and status description.
response.Redirect(@"http://www.contoso.com/indexServer/index.html");
}
}

Remarks
The Redirect method is used to redirect a client to the new location for a resource. This method sets the response's
Location header to url , the StatusCode property to Redirect, and the StatusDescription property to "Found".
HttpListenerResponse.RedirectLocation HttpListener
Response.RedirectLocation
I n this Article
Gets or sets the value of the HTTP Location header in this response.

public string RedirectLocation { get; set; }


member this.RedirectLocation : string with get, set

Returns
String String
A String that contains the absolute URL to be sent to the client in the Location header.

Exceptions
ArgumentException ArgumentException
The value specified for a set operation is an empty string ("").
ObjectDisposedException ObjectDisposedException
This object is closed.

Examples
The following code example demonstrates setting this property.
public static void TemporaryRedirect(HttpListenerRequest request, HttpListenerResponse response)
{
if (request.Url.OriginalString == @"http://www.contoso.com/index.html")
{
response.RedirectLocation = @"http://www.contoso.com/indexServer/index.html";
}
}

Remarks
The Location header specifies the URL to which the client is directed to locate a requested resource.
Note

Setting this property does not automatically set the StatusCode property.
HttpListenerResponse.SendChunked HttpListener
Response.SendChunked
I n this Article
Gets or sets whether the response uses chunked transfer encoding.

public bool SendChunked { get; set; }


member this.SendChunked : bool with get, set

Returns
Boolean Boolean
true if the response is set to use chunked transfer encoding; otherwise, false . The default is false .

Remarks
The body of a chunked message is made up of a series of chunks. Each chunk comprises of two parts - the size of the
chunk data and the actual data. When set to true the response is sent using chunked transfer encoding.
HttpListenerResponse.SetCookie HttpListenerResponse.
SetCookie
I n this Article
Adds or updates a Cookie in the collection of cookies sent with this response.

public void SetCookie (System.Net.Cookie cookie);


member this.SetCookie : System.Net.Cookie -> unit

Parameters
cookie Cookie Cookie
A Cookie for this response.
Exceptions
ArgumentNullException ArgumentNullException
cookie is null .
ArgumentException ArgumentException
The cookie already exists in the collection and could not be replaced.

Examples
The following code example demonstrates calling this method.
// This example requires the System and System.Net namespaces.
public static void SimpleCookieExample(string[] prefixes)
{
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;

// This application sends a cookie to the client marking the time


// they visited.
Cookie timeStampCookie = new Cookie("VisitDate", DateTime.Now.ToString());
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Add the cookie to the response.
response.SetCookie(timeStampCookie);
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
response.ContentEncoding = System.Text.Encoding.UTF8;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Send the response.
response.Close(buffer, true);
listener.Stop();
}
Remarks
Two cookies are considered the same if the values of their Name, Domain, and Path properties are the same. If these
three pieces of information are the same, the method attempts to update the cookie. The name and domain
comparisons are not case sensitive, but the path comparison is case sensitive.
HttpListenerResponse.StatusCode HttpListenerResponse.
StatusCode
I n this Article
Gets or sets the HTTP status code to be returned to the client.

public int StatusCode { get; set; }


member this.StatusCode : int with get, set

Returns
Int32 Int32
An Int32 value that specifies the HTTP status code for the requested resource. The default is OK, indicating that the
server successfully processed the client's request and included the requested resource in the response body.
Exceptions
ObjectDisposedException ObjectDisposedException
This object is closed.
ProtocolViolationException ProtocolViolationException
The value specified for a set operation is not valid. Valid values are between 100 and 999 inclusive.

Examples
The following code example demonstrates setting the value of this property.
public static string[] CopyPrefixes (HttpListener listener)
{
HttpListenerPrefixCollection prefixes = listener.Prefixes;
string[] prefixArray = new string[prefixes.Count];
prefixes.CopyTo(prefixArray, 0);
return prefixArray;
}

Remarks
Clients use the status code returned by the server to decide how to proceed. A value of OK indicates that the server
successfully processed the client's request and included the requested resource in the response body. Other common
status codes include NotFound, indicating that the requested resource was not found on the server, and NotModified,
indicating that it was unnecessary to return the requested resource in the response body because the client's cached
copy of the resource is up-to-date.
For a complete list of possible status codes, see the HttpStatusCode enumeration.
HttpListenerResponse.StatusDescription HttpListener
Response.StatusDescription
I n this Article
Gets or sets a text description of the HTTP status code returned to the client.

public string StatusDescription { get; set; }


member this.StatusDescription : string with get, set

Returns
String String
The text description of the HTTP status code returned to the client. The default is the RFC 2616 description for the
StatusCode property value, or an empty string ("") if an RFC 2616 description does not exist.
Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation is null .

ArgumentException ArgumentException
The value specified for a set operation contains non-printable characters.

Examples
The following code example demonstrates setting the value of this property.
// When the client is not authenticated, there is no Identity.
if (context.User == null)
{
message.Append ("<HTML><BODY><p> Hello local user! </p></BODY></HTML>");
}
else
{
// Get the requester's identity.
System.Security.Principal.WindowsIdentity identity = WindowsIdentity.GetCurrent();
// Construct the response body.
message.AppendFormat ("<HTML><BODY><p> Hello {0}!<br/>",
identity.Name);
message.AppendFormat ("You were authenticated using {0}.</p>",
identity.AuthenticationType);
message.Append ("</BODY></HTML>");
}

// Configure the response.


HttpListenerResponse response = context.Response;

// Use the encoding from the response if one has been set.
// Otherwise, use UTF8.
System.Text.Encoding encoding = response.ContentEncoding;
if (encoding == null)
{
encoding = System.Text.Encoding.UTF8;
response.ContentEncoding = encoding;
}
byte[] buffer = encoding.GetBytes (message.ToString ());
response.ContentLength64 = buffer.Length;
response.StatusCode = (int) HttpStatusCode.OK;
response.StatusDescription = "OK";
response.ProtocolVersion = new Version ("1.1");
// Don't keep the TCP connection alive;
// We don't expect multiple requests from the same client.
response.KeepAlive = false;
// Write the response body.
System.IO.Stream stream = response.OutputStream;
stream.Write(buffer, 0, buffer.Length);

Remarks
The status description typically provides details that explain the StatusCode value.
HttpListenerTimeoutManager HttpListenerTimeout
Manager Class
The timeout manager to use for an HttpListener object.

D eclaration
public class HttpListenerTimeoutManager
type HttpListenerTimeoutManager = class

I nheritance H ierarchy
Object Object

Remarks
The timeout manager defines the connection timeout limits for a HttpListener instance.

Constructors
HttpListenerTimeoutManager()
HttpListenerTimeoutManager()

Properties
DrainEntityBody
DrainEntityBody

Gets or sets the time allowed for the HttpListener to drain the entity body on a Keep-Alive connection.

EntityBody
EntityBody

Gets or sets the time allowed for the request entity body to arrive.

HeaderWait
HeaderWait

Gets or sets the time allowed for the HttpListener to parse the request header.

IdleConnection
IdleConnection

Gets or sets the time allowed for an idle connection.

MinSendBytesPerSecond
MinSendBytesPerSecond

Gets or sets the minimum send rate, in bytes-per-second, for the response.

RequestQueue
RequestQueue

Gets or sets the time allowed for the request to remain in the request queue before the HttpListener picks it up.
HttpListenerTimeoutManager.DrainEntityBody Http
ListenerTimeoutManager.DrainEntityBody
I n this Article
Gets or sets the time allowed for the HttpListener to drain the entity body on a Keep-Alive connection.

public TimeSpan DrainEntityBody { get; set; }


member this.DrainEntityBody : TimeSpan with get, set

Returns
TimeSpan TimeSpan
The time allowed for the HttpListener to drain the entity body on a Keep-Alive connection.

Remarks
The default value for this property is 2 minutes.
On a Keep-Alive connection, after the app has sent a response for a request and before the request entity body has
completely arrived, the HttpListener starts draining the remainder of the entity body to reach another potentially
pipelined request from the client. If the time to drain the remaining entity body exceeds the allowed period the
connection is timed out.
HttpListenerTimeoutManager.EntityBody HttpListener
TimeoutManager.EntityBody
I n this Article
Gets or sets the time allowed for the request entity body to arrive.

public TimeSpan EntityBody { get; set; }


member this.EntityBody : TimeSpan with get, set

Returns
TimeSpan TimeSpan
The time allowed for the request entity body to arrive.

Remarks
The default value for this property is 2 minutes.
The HttpListener turns on this timer when the request has an entity body. The timer expiration is initially set to the
configured value. When the HttpListener receives additional data indications on the request, it resets the timer to give
the connection another interval.
HttpListenerTimeoutManager.HeaderWait HttpListener
TimeoutManager.HeaderWait
I n this Article
Gets or sets the time allowed for the HttpListener to parse the request header.

public TimeSpan HeaderWait { get; set; }


member this.HeaderWait : TimeSpan with get, set

Returns
TimeSpan TimeSpan
The time allowed for the HttpListener to parse the request header.

Remarks
The default value for this property is 2 minutes.
This timeout is only enforced after the first request on the connection is routed to the HttpListener.
The system cannot determine the request queue or URL group that the request is associated with until the headers
have been parsed. Therefore, the HttpListener enforces the default HeaderWait timer for the first request on a
connection. Subsequent requests on a Keep-Alive connection will use the value set on this property.
HttpListenerTimeoutManager
I n this Article
public HttpListenerTimeoutManager ();
HttpListenerTimeoutManager.IdleConnection Http
ListenerTimeoutManager.IdleConnection
I n this Article
Gets or sets the time allowed for an idle connection.

public TimeSpan IdleConnection { get; set; }


member this.IdleConnection : TimeSpan with get, set

Returns
TimeSpan TimeSpan
The time allowed for an idle connection.

Remarks
The default value for this property is 2 minutes.
This timeout is only enforced after the first request on the connection is routed to the HttpListener.
The system cannot determine the request queue or URL group that the request is associated with until the headers
have been parsed. Therefore, the HttpListener enforces the default IdleConnection timer for the first request on a
connection. Subsequent requests on a Keep-Alive connection will use the value set on this property.
HttpListenerTimeoutManager.MinSendBytesPerSecond
HttpListenerTimeoutManager.MinSendBytesPerSecond
I n this Article
Gets or sets the minimum send rate, in bytes-per-second, for the response.

public long MinSendBytesPerSecond { get; set; }


member this.MinSendBytesPerSecond : int64 with get, set

Returns
Int64 Int64
The minimum send rate, in bytes-per-second, for the response.

Remarks
The default response send rate is 150 bytes-per-second.
To disable this timer, set MinSendBytesPerSecond to MAXULONG.
HttpListenerTimeoutManager.RequestQueue Http
ListenerTimeoutManager.RequestQueue
I n this Article
Gets or sets the time allowed for the request to remain in the request queue before the HttpListener picks it up.

public TimeSpan RequestQueue { get; set; }


member this.RequestQueue : TimeSpan with get, set

Returns
TimeSpan TimeSpan
The time allowed for the request to remain in the request queue before the HttpListener picks it up.

Remarks
The default value for this property is 2 minutes.
HttpRequestHeader HttpRequestHeader Enum
The HTTP headers that may be specified in a client request.

D eclaration
public enum HttpRequestHeader
type HttpRequestHeader =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The appropriate contents of various headers are described in detail in the HTTP/1.1 specification, available at rfc2616.

Fields
Accept Accept The Accept header, which specifies the MIME types that are acceptable for the response.

AcceptCharset The Accept-Charset header, which specifies the character sets that are acceptable for the response.
AcceptCharset

AcceptEncoding The Accept-Encoding header, which specifies the content encodings that are acceptable for the
AcceptEncoding response.

AcceptLanguage The Accept-Language header, which specifies that natural languages that are preferred for the
AcceptLanguage response.

Allow Allow The Allow header, which specifies the set of HTTP methods supported.

Authorization The Authorization header, which specifies the credentials that the client presents in order to
Authorization authenticate itself to the server.

CacheControl The Cache-Control header, which specifies directives that must be obeyed by all cache control
CacheControl mechanisms along the request/response chain.

Connection The Connection header, which specifies options that are desired for a particular connection.
Connection
ContentEncoding The Content-Encoding header, which specifies the encodings that have been applied to the
ContentEncoding accompanying body data.

ContentLanguage The Content-Language header, which specifies the natural language(s) of the accompanying body
ContentLanguage data.

ContentLength The Content-Length header, which specifies the length, in bytes, of the accompanying body data.
ContentLength

ContentLocation The Content-Location header, which specifies a URI from which the accompanying body may be
ContentLocation obtained.

ContentMd5 The Content-MD5 header, which specifies the MD5 digest of the accompanying body data, for the
ContentMd5 purpose of providing an end-to-end message integrity check.

ContentRange The Content-Range header, which specifies where in the full body the accompanying partial body
ContentRange data should be applied.

ContentType The Content-Type header, which specifies the MIME type of the accompanying body data.
ContentType

Cookie Cookie The Cookie header, which specifies cookie data presented to the server.

Date Date The Date header, which specifies the date and time at which the request originated.

Expect Expect The Expect header, which specifies particular server behaviors that are required by the client.

Expires Expires The Expires header, which specifies the date and time after which the accompanying body data
should be considered stale.

From From The From header, which specifies an Internet Email address for the human user who controls the
requesting user agent.

Host Host The Host header, which specifies the host name and port number of the resource being requested.

IfMatch IfMatch The If-Match header, which specifies that the requested operation should be performed only if the
client's cached copy of the indicated resource is current.
IfModifiedSince The If-Modified-Since header, which specifies that the requested operation should be performed
IfModifiedSince only if the requested resource has been modified since the indicated data and time.

IfNoneMatch The If-None-Match header, which specifies that the requested operation should be performed only if
IfNoneMatch none of client's cached copies of the indicated resources are current.

IfRange IfRange The If-Range header, which specifies that only the specified range of the requested resource should
be sent, if the client's cached copy is current.

IfUnmodifiedSince The If-Unmodified-Since header, which specifies that the requested operation should be performed
IfUnmodifiedSince only if the requested resource has not been modified since the indicated date and time.

KeepAlive The Keep-Alive header, which specifies a parameter used into order to maintain a persistent
KeepAlive connection.

LastModified The Last-Modified header, which specifies the date and time at which the accompanying body data
LastModified was last modified.

MaxForwards The Max-Forwards header, which specifies an integer indicating the remaining number of times that
MaxForwards this request may be forwarded.

Pragma Pragma The Pragma header, which specifies implementation-specific directives that might apply to any agent
along the request/response chain.

ProxyAuthorization The Proxy-Authorization header, which specifies the credentials that the client presents in order to
ProxyAuthorization authenticate itself to a proxy.

Range Range The Range header, which specifies the sub-range(s) of the response that the client requests be
returned in lieu of the entire response.

Referer Referer The Referer header, which specifies the URI of the resource from which the request URI was
obtained.

Te Te The TE header, which specifies the transfer encodings that are acceptable for the response.

Trailer Trailer The Trailer header, which specifies the header fields present in the trailer of a message encoded with
chunked transfer-coding.
TransferEncoding The Transfer-Encoding header, which specifies what (if any) type of transformation that has been
TransferEncoding applied to the message body.

Translate The Translate header, a Microsoft extension to the HTTP specification used in conjunction with
Translate WebDAV functionality.

Upgrade Upgrade The Upgrade header, which specifies additional communications protocols that the client supports.

UserAgent The User-Agent header, which specifies information about the client agent.
UserAgent

Via Via The Via header, which specifies intermediate protocols to be used by gateway and proxy agents.

Warning Warning The Warning header, which specifies additional information about that status or transformation of a
message that might not be reflected in the message.
HttpResponseHeader HttpResponseHeader Enum
The HTTP headers that can be specified in a server response.

D eclaration
public enum HttpResponseHeader
type HttpResponseHeader =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The appropriate contents of various headers are described in detail in the HTTP/1.1 specification.

Fields
AcceptRanges The Accept-Ranges header, which specifies the range that is accepted by the server.
AcceptRanges

Age Age The Age header, which specifies the time, in seconds, since the response was generated by the
originating server.

Allow Allow The Allow header, which specifies the set of HTTP methods that are supported.

CacheControl The Cache-Control header, which specifies caching directives that must be obeyed by all caching
CacheControl mechanisms along the request/response chain.

Connection The Connection header, which specifies options that are desired for a particular connection.
Connection

ContentEncoding The Content-Encoding header, which specifies the encodings that have been applied to the
ContentEncoding accompanying body data.

ContentLanguage The Content-Language header, which specifies the natural language or languages of the
ContentLanguage accompanying body data.

ContentLength The Content-Length header, which specifies the length, in bytes, of the accompanying body data.
ContentLength
ContentLocation The Content-Location header, which specifies a URI from which the accompanying body can be
ContentLocation obtained.

ContentMd5 The Content-MD5 header, which specifies the MD5 digest of the accompanying body data, for the
ContentMd5 purpose of providing an end-to-end message integrity check.

ContentRange The Range header, which specifies the subrange or subranges of the response that the client
ContentRange requests be returned in lieu of the entire response.

ContentType The Content-Type header, which specifies the MIME type of the accompanying body data.
ContentType

Date Date The Date header, which specifies the date and time at which the response originated.

ETag ETag The Etag header, which specifies the current value for the requested variant.

Expires Expires The Expires header, which specifies the date and time after which the accompanying body data
should be considered stale.

KeepAlive KeepAlive The Keep-Alive header, which specifies a parameter to be used to maintain a persistent
connection.

LastModified The Last-Modified header, which specifies the date and time at which the accompanying body
LastModified data was last modified.

Location Location The Location header, which specifies a URI to which the client is redirected to obtain the requested
resource.

Pragma Pragma The Pragma header, which specifies implementation-specific directives that might apply to any
agent along the request/response chain.

ProxyAuthenticate The Proxy-Authenticate header, which specifies that the client must authenticate itself to a proxy.
ProxyAuthenticate

RetryAfter The Retry-After header, which specifies a time (in seconds), or a date and time, after which the
RetryAfter client can retry its request.

Server Server The Server header, which specifies information about the originating server agent.
SetCookie SetCookie The Set-Cookie header, which specifies cookie data that is presented to the client.

Trailer Trailer The Trailer header, which specifies that the indicated header fields are present in the trailer of a
message that is encoded with chunked transfer-coding.

TransferEncoding The Transfer-Encoding header, which specifies what (if any) type of transformation has been
TransferEncoding applied to the message body.

Upgrade Upgrade The Upgrade header, which specifies additional communications protocols that the client supports.

Vary Vary The Vary header, which specifies the request headers that are used to determine whether a cached
response is fresh.

Via Via The Via header, which specifies intermediate protocols to be used by gateway and proxy agents.

Warning Warning The Warning header, which specifies additional information about that status or transformation of
a message that might not be reflected in the message.

WwwAuthenticate The WWW-Authenticate header, which specifies that the client must authenticate itself to the
WwwAuthenticate server.
HttpStatusCode HttpStatusCode Enum
Contains the values of status codes defined for HTTP.

D eclaration
public enum HttpStatusCode
type HttpStatusCode =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The HttpStatusCode enumeration contains the values of the status codes defined in RFC 2616 for HTTP 1.1.
The status of an HTTP request is contained in the HttpWebResponse.StatusCode property.
If the HttpWebRequest.AllowAutoRedirect property is false , the following enumeration values cause an exception to
be thrown:
Ambiguous
Found
MultipleChoices
Redirect
RedirectKeepVerb
RedirectMethod
SeeOther
TemporaryRedirect

Fields
Accepted Accepted Equivalent to HTTP status 202. Accepted indicates that the request has been accepted
for further processing.

AlreadyReported
AlreadyReported

Ambiguous Ambiguous Equivalent to HTTP status 300. Ambiguous indicates that the requested information
has multiple representations. The default action is to treat this status as a redirect and
follow the contents of the Location header associated with this response. Ambiguous
is a synonym for MultipleChoices .

BadGateway BadGateway Equivalent to HTTP status 502. BadGateway indicates that an intermediate proxy
server received a bad response from another proxy or the origin server.
BadRequest BadRequest Equivalent to HTTP status 400. BadRequest indicates that the request could not be
understood by the server. BadRequest is sent when no other error is applicable, or if
the exact error is unknown or does not have its own error code.

Conflict Conflict Equivalent to HTTP status 409. Conflict indicates that the request could not be carried
out because of a conflict on the server.

Continue Continue Equivalent to HTTP status 100. Continue indicates that the client can continue with its
request.

Created Created Equivalent to HTTP status 201. Created indicates that the request resulted in a new
resource created before the response was sent.

EarlyHints EarlyHints

ExpectationFailed Equivalent to HTTP status 417. ExpectationFailed indicates that an expectation given in
ExpectationFailed an Expect header could not be met by the server.

FailedDependency
FailedDependency

Forbidden Forbidden Equivalent to HTTP status 403. Forbidden indicates that the server refuses to fulfill the
request.

Found Found Equivalent to HTTP status 302. Found indicates that the requested information is
located at the URI specified in the Location header. The default action when this status
is received is to follow the Location header associated with the response. When the
original request method was POST, the redirected request will use the GET method.
Found is a synonym for Redirect .

GatewayTimeout Equivalent to HTTP status 504. GatewayTimeout indicates that an intermediate proxy
GatewayTimeout server timed out while waiting for a response from another proxy or the origin server.

Gone Gone Equivalent to HTTP status 410. Gone indicates that the requested resource is no
longer available.

HttpVersionNotSupported Equivalent to HTTP status 505. HttpVersionNotSupported indicates that the requested
HttpVersionNotSupported HTTP version is not supported by the server.

IMUsed IMUsed
InsufficientStorage
InsufficientStorage

InternalServerError Equivalent to HTTP status 500. InternalServerError indicates that a generic error has
InternalServerError occurred on the server.

LengthRequired Equivalent to HTTP status 411. LengthRequired indicates that the required Content-
LengthRequired length header is missing.

Locked Locked

LoopDetected LoopDetected

MethodNotAllowed Equivalent to HTTP status 405. MethodNotAllowed indicates that the request method
MethodNotAllowed (POST or GET) is not allowed on the requested resource.

MisdirectedRequest
MisdirectedRequest

Moved Moved Equivalent to HTTP status 301. Moved indicates that the requested information has
been moved to the URI specified in the Location header. The default action when this
status is received is to follow the Location header associated with the response. When
the original request method was POST, the redirected request will use the GET
method. Moved is a synonym for MovedPermanently .

MovedPermanently Equivalent to HTTP status 301. MovedPermanently indicates that the requested
MovedPermanently information has been moved to the URI specified in the Location header. The default
action when this status is received is to follow the Location header associated with the
response. MovedPermanently is a synonym for Moved .

MultipleChoices Equivalent to HTTP status 300. MultipleChoices indicates that the requested
MultipleChoices information has multiple representations. The default action is to treat this status as a
redirect and follow the contents of the Location header associated with this response.
MultipleChoices is a synonym for Ambiguous .

MultiStatus MultiStatus

NetworkAuthenticationRequired
NetworkAuthenticationRequired

NoContent NoContent Equivalent to HTTP status 204. NoContent indicates that the request has been
successfully processed and that the response is intentionally blank.
NonAuthoritativeInformation Equivalent to HTTP status 203. NonAuthoritativeInformation indicates that the
NonAuthoritativeInformation returned metainformation is from a cached copy instead of the origin server and
therefore may be incorrect.

NotAcceptable NotAcceptable Equivalent to HTTP status 406. NotAcceptable indicates that the client has indicated
with Accept headers that it will not accept any of the available representations of the
resource.

NotExtended NotExtended

NotFound NotFound Equivalent to HTTP status 404. NotFound indicates that the requested resource does
not exist on the server.

NotImplemented Equivalent to HTTP status 501. NotImplemented indicates that the server does not
NotImplemented support the requested function.

NotModified NotModified Equivalent to HTTP status 304. NotModified indicates that the client's cached copy is
up to date. The contents of the resource are not transferred.

OK OK Equivalent to HTTP status 200. OK indicates that the request succeeded and that the
requested information is in the response. This is the most common status code to
receive.

PartialContent Equivalent to HTTP status 206. PartialContent indicates that the response is a partial
PartialContent response as requested by a GET request that includes a byte range.

PaymentRequired Equivalent to HTTP status 402. PaymentRequired is reserved for future use.
PaymentRequired

PermanentRedirect
PermanentRedirect

PreconditionFailed Equivalent to HTTP status 412. PreconditionFailed indicates that a condition set for
PreconditionFailed this request failed, and the request cannot be carried out. Conditions are set with
conditional request headers like If-Match, If-None-Match, or If-Unmodified-Since.

PreconditionRequired
PreconditionRequired

Processing Processing
ProxyAuthenticationRequired Equivalent to HTTP status 407. ProxyAuthenticationRequired indicates that the
ProxyAuthenticationRequired requested proxy requires authentication. The Proxy-authenticate header contains the
details of how to perform the authentication.

Redirect Redirect Equivalent to HTTP status 302. Redirect indicates that the requested information is
located at the URI specified in the Location header. The default action when this status
is received is to follow the Location header associated with the response. When the
original request method was POST, the redirected request will use the GET method.
Redirect is a synonym for Found .

RedirectKeepVerb Equivalent to HTTP status 307. RedirectKeepVerb indicates that the request
RedirectKeepVerb information is located at the URI specified in the Location header. The default action
when this status is received is to follow the Location header associated with the
response. When the original request method was POST, the redirected request will also
use the POST method. RedirectKeepVerb is a synonym for TemporaryRedirect .

RedirectMethod Equivalent to HTTP status 303. RedirectMethod automatically redirects the client to
RedirectMethod the URI specified in the Location header as the result of a POST. The request to the
resource specified by the Location header will be made with a GET. RedirectMethod
is a synonym for SeeOther .

RequestedRangeNotSatisfiable Equivalent to HTTP status 416. RequestedRangeNotSatisfiable indicates that the range
RequestedRangeNotSatisfiable of data requested from the resource cannot be returned, either because the beginning
of the range is before the beginning of the resource, or the end of the range is after
the end of the resource.

RequestEntityTooLarge Equivalent to HTTP status 413. RequestEntityTooLarge indicates that the request is
RequestEntityTooLarge too large for the server to process.

RequestHeaderFieldsTooLarge
RequestHeaderFieldsTooLarge

RequestTimeout Equivalent to HTTP status 408. RequestTimeout indicates that the client did not send a
RequestTimeout request within the time the server was expecting the request.

RequestUriTooLong Equivalent to HTTP status 414. RequestUriTooLong indicates that the URI is too long.
RequestUriTooLong

ResetContent ResetContent Equivalent to HTTP status 205. ResetContent indicates that the client should reset (not
reload) the current resource.

SeeOther SeeOther Equivalent to HTTP status 303. SeeOther automatically redirects the client to the URI
specified in the Location header as the result of a POST. The request to the resource
specified by the Location header will be made with a GET. SeeOther is a synonym for
RedirectMethod
ServiceUnavailable Equivalent to HTTP status 503. ServiceUnavailable indicates that the server is
ServiceUnavailable temporarily unavailable, usually due to high load or maintenance.

SwitchingProtocols Equivalent to HTTP status 101. SwitchingProtocols indicates that the protocol version
SwitchingProtocols or protocol is being changed.

TemporaryRedirect Equivalent to HTTP status 307. TemporaryRedirect indicates that the request
TemporaryRedirect information is located at the URI specified in the Location header. The default action
when this status is received is to follow the Location header associated with the
response. When the original request method was POST, the redirected request will also
use the POST method. TemporaryRedirect is a synonym for RedirectKeepVerb .

TooManyRequests
TooManyRequests

Unauthorized Unauthorized Equivalent to HTTP status 401. Unauthorized indicates that the requested resource
requires authentication. The WWW-Authenticate header contains the details of how to
perform the authentication.

UnavailableForLegalReasons
UnavailableForLegalReasons

UnprocessableEntity
UnprocessableEntity

UnsupportedMediaType Equivalent to HTTP status 415. UnsupportedMediaType indicates that the request is
UnsupportedMediaType an unsupported type.

Unused Unused Equivalent to HTTP status 306. Unused is a proposed extension to the HTTP/1.1
specification that is not fully specified.

UpgradeRequired Equivalent to HTTP status 426. UpgradeRequired indicates that the client should
UpgradeRequired switch to a different protocol such as TLS/1.0.

UseProxy UseProxy Equivalent to HTTP status 305. UseProxy indicates that the request should use the
proxy server at the URI specified in the Location header.

VariantAlsoNegotiates
VariantAlsoNegotiates
HttpVersion HttpVersion Class
Defines the HTTP version numbers that are supported by the HttpWebRequest and HttpWebResponse classes.

D eclaration
public class HttpVersion
type HttpVersion = class

I nheritance H ierarchy
Object Object

Remarks
The HttpVersion class defines the HTTP versions that are supported by the HttpWebRequest and HttpWebResponse
classes. The HTTP version number is used to control version-specific features of HTTP, such as pipelining and
chunking.

Constructors
HttpVersion()
HttpVersion()

Initializes a new instance of the HttpVersion class.

Fields
Unknown
Unknown

Version10
Version10

Defines a Version instance for HTTP 1.0.

Version11
Version11

Defines a Version instance for HTTP 1.1.

Version20
Version20
HttpVersion
I n this Article
Initializes a new instance of the HttpVersion class.
public HttpVersion ();
HttpVersion.Unknown HttpVersion.Unknown
I n this Article
public static readonly Version Unknown;
staticval mutable Unknown : Version

Returns
Version Version
HttpVersion.Version10 HttpVersion.Version10
I n this Article
Defines a Version instance for HTTP 1.0.
public static readonly Version Version10;
staticval mutable Version10 : Version

Returns
Version Version
HttpVersion.Version11 HttpVersion.Version11
I n this Article
Defines a Version instance for HTTP 1.1.
public static readonly Version Version11;
staticval mutable Version11 : Version

Returns
Version Version
HttpVersion.Version20 HttpVersion.Version20
I n this Article
public static readonly Version Version20;
staticval mutable Version20 : Version

Returns
Version Version
HttpWebRequest HttpWebRequest Class
Provides an HTTP -specific implementation of the WebRequest class.

D eclaration
[System.Serializable]
public class HttpWebRequest : System.Net.WebRequest, System.Runtime.Serialization.ISerializable
type HttpWebRequest = class
inherit WebRequest
interface ISerializable

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
WebRequest WebRequest

Remarks
Im p o rt a nt

We don't recommend that you use HttpWebRequest for new development. Instead, use the System.Net.Http.HttpClient
class.
The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional
properties and methods that enable the user to interact directly with servers using HTTP.
Do not use the HttpWebRequest constructor. Use the WebRequest.Create method to initialize new HttpWebRequest
objects. If the scheme for the Uniform Resource Identifier (URI) is http:// or https:// , Create returns an
HttpWebRequest object.
The GetResponse method makes a synchronous request to the resource specified in the RequestUri property and
returns an HttpWebResponse that contains the response object. The response data can be received by using the stream
returned by GetResponseStream. If the response object or the response stream is closed, remaining data will be
forfeited. The remaining data will be drained and the socket will be re-used for subsequent requests when closing the
response object or stream if the following conditions hold: it's a keep-alive or pipelined request, only a small amount of
data needs to be received, or the remaining data is received in a small time interval. If none of the mentioned
conditions hold or the drain time is exceeded, the socket will be closed. For keep-alive or pipelined connections, we
strongly recommend that the application reads the streams until EOF. This ensures that the socket will be re-used for
subsequent requests resulting in better performance and less resources used.
When you want to send data to the resource, the GetRequestStream method returns a Stream object to use to send
data. The BeginGetRequestStream and EndGetRequestStream methods provide asynchronous access to the send data
stream.
For client authentication with HttpWebRequest, the client certificate must be installed in the My certificate store of the
current user.
The HttpWebRequest class throws a WebException when errors occur while accessing a resource. The
WebException.Status property contains a WebExceptionStatus value that indicates the source of the error. When
WebException.Status is WebExceptionStatus.ProtocolError, the Response property contains the HttpWebResponse
received from the resource.
HttpWebRequest exposes common HTTP header values sent to the Internet resource as properties, set by methods, or
set by the system; the following table contains a complete list. You can set other headers in the Headers property as
name/value pairs. Note that servers and caches may change or add headers during the request.
The following table lists the HTTP headers that are set either by properties or methods or the system.

HE AD ER SET BY

Accept Set by the Accept property.

Connection Set by the Connection property, KeepAlive property.

Content-Length Set by the ContentLength property.

Content-Type Set by the ContentType property.

Expect Set by the Expect property.

Date Set by the system to current date.

Host Set by the system to current host information.

If-Modified-Since Set by the IfModifiedSince property.

Range Set by the AddRange method.

Referer Set by the Referer property.

Transfer-Encoding Set by the TransferEncoding property (the SendChunked


property must be true ).

User-Agent Set by the UserAgent property.


Note

HttpWebRequest is registered automatically. You do not need to call the RegisterPrefix method to register
System.Net.HttpWebRequest before using URIs beginning with http:// or https:// .
The local computer or application config file may specify that a default proxy be used. If the Proxy property is specified,
then the proxy settings from the Proxy property override the local computer or application config file and the
HttpWebRequest instance will use the proxy settings specified. If no proxy is specified in a config file and the Proxy
property is unspecified, the HttpWebRequest class uses the proxy settings inherited from Internet Explorer on the local
computer. If there are no proxy settings in Internet Explorer, the request is sent directly to the server.
The HttpWebRequest class parses a proxy bypass list with wildcard characters inherited from Internet Explorer
differently than the bypass list is parsed directly by Internet Explorer. For example, the HttpWebRequest class will parse
a bypass list of "nt*" from Internet Explorer as a regular expression of "nt.$". This differs from the native behavior of
Internet Explorer. So a URL of " http://intxxxxx " would bypass the proxy using the HttpWebRequest class, but would
not bypass the proxy using Internet Explorer.
Note

The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if
possible. When attempting to reuse an SSL session, the Framework uses the first element of ClientCertificates (if there
is one), or tries to reuse an anonymous sessions if ClientCertificates is empty.
Note

For security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to
enable cookies.
The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for
connections. Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient,
SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default.
Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services
OR TLS w/ RC4 services. This article explains how to modify your code so that the new behavior is disabled.

Constructors
HttpWebRequest()
HttpWebRequest()

Initializes a new instance of the HttpWebRequest class. This constructor is obsolete.

HttpWebRequest(Uri)
HttpWebRequest(Uri)

HttpWebRequest(SerializationInfo, StreamingContext)
HttpWebRequest(SerializationInfo, StreamingContext)

Initializes a new instance of the HttpWebRequest class from the specified instances of the SerializationInfo and
StreamingContext classes. This constructor is obsolete.

Properties
Accept
Accept

Gets or sets the value of the Accept HTTP header.

Address
Address

Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request.

AllowAutoRedirect
AllowAutoRedirect

Gets or sets a value that indicates whether the request should follow redirection responses.

AllowReadStreamBuffering
AllowReadStreamBuffering

Gets or sets a value that indicates whether to buffer the received from the Internet resource.
AllowWriteStreamBuffering
AllowWriteStreamBuffering

Gets or sets a value that indicates whether to buffer the data sent to the Internet resource.

AutomaticDecompression
AutomaticDecompression

Gets or sets the type of decompression that is used.

ClientCertificates
ClientCertificates

Gets or sets the collection of security certificates that are associated with this request.

Connection
Connection

Gets or sets the value of the Connection HTTP header.

ConnectionGroupName
ConnectionGroupName

Gets or sets the name of the connection group for the request.

ContentLength
ContentLength

Gets or sets the Content-length HTTP header.

ContentType
ContentType

Gets or sets the value of the Content-type HTTP header.

ContinueDelegate
ContinueDelegate

Gets or sets the delegate method called when an HTTP 100-continue response is received from the Internet
resource.

ContinueTimeout
ContinueTimeout

Gets or sets a timeout, in milliseconds, to wait until the 100-Continue is received from the server.

CookieContainer
CookieContainer

Gets or sets the cookies associated with the request.

Credentials
Credentials

Gets or sets authentication information for the request.

Date
Date

Gets or sets the Date HTTP header value to use in an HTTP request.

DefaultCachePolicy
DefaultCachePolicy

Gets or sets the default cache policy for this request.

DefaultMaximumErrorResponseLength
DefaultMaximumErrorResponseLength

Gets or sets the default maximum length of an HTTP error response.

DefaultMaximumResponseHeadersLength
DefaultMaximumResponseHeadersLength

Gets or sets the default for the MaximumResponseHeadersLength property.

Expect
Expect

Gets or sets the value of the Expect HTTP header.

HaveResponse
HaveResponse

Gets a value that indicates whether a response has been received from an Internet resource.
Headers
Headers

Specifies a collection of the name/value pairs that make up the HTTP headers.

Host
Host

Gets or sets the Host header value to use in an HTTP request independent from the request URI.

IfModifiedSince
IfModifiedSince

Gets or sets the value of the If-Modified-Since HTTP header.

KeepAlive
KeepAlive

Gets or sets a value that indicates whether to make a persistent connection to the Internet resource.

MaximumAutomaticRedirections
MaximumAutomaticRedirections

Gets or sets the maximum number of redirects that the request follows.

MaximumResponseHeadersLength
MaximumResponseHeadersLength

Gets or sets the maximum allowed length of the response headers.

MediaType
MediaType

Gets or sets the media type of the request.

Method
Method

Gets or sets the method for the request.

Pipelined
Pipelined

Gets or sets a value that indicates whether to pipeline the request to the Internet resource.
PreAuthenticate
PreAuthenticate

Gets or sets a value that indicates whether to send an Authorization header with the request.

ProtocolVersion
ProtocolVersion

Gets or sets the version of HTTP to use for the request.

Proxy
Proxy

Gets or sets proxy information for the request.

ReadWriteTimeout
ReadWriteTimeout

Gets or sets a time-out in milliseconds when writing to or reading from a stream.

Referer
Referer

Gets or sets the value of the Referer HTTP header.

RequestUri
RequestUri

Gets the original Uniform Resource Identifier (URI) of the request.

SendChunked
SendChunked

Gets or sets a value that indicates whether to send data in segments to the Internet resource.

ServerCertificateValidationCallback
ServerCertificateValidationCallback

Gets or sets a callback function to validate the server certificate.

ServicePoint
ServicePoint

Gets the service point to use for the request.


SupportsCookieContainer
SupportsCookieContainer

Gets a value that indicates whether the request provides support for a CookieContainer.

Timeout
Timeout

Gets or sets the time-out value in milliseconds for the GetResponse() and GetRequestStream() methods.

TransferEncoding
TransferEncoding

Gets or sets the value of the Transfer-encoding HTTP header.

UnsafeAuthenticatedConnectionSharing
UnsafeAuthenticatedConnectionSharing

Gets or sets a value that indicates whether to allow high-speed NTLM -authenticated connection sharing.

UseDefaultCredentials
UseDefaultCredentials

Gets or sets a Boolean value that controls whether default credentials are sent with requests.

UserAgent
UserAgent

Gets or sets the value of the User-agent HTTP header.

Methods
Abort()
Abort()

Cancels a request to an Internet resource.

AddRange(Int32)
AddRange(Int32)

Adds a byte range header to a request for a specific range from the beginning or end of the requested data.

AddRange(Int64)
AddRange(Int64)

Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
AddRange(Int32, Int32)
AddRange(Int32, Int32)

Adds a byte range header to the request for a specified range.

AddRange(Int64, Int64)
AddRange(Int64, Int64)

Adds a byte range header to the request for a specified range.

AddRange(String, Int32)
AddRange(String, Int32)

Adds a Range header to a request for a specific range from the beginning or end of the requested data.

AddRange(String, Int64)
AddRange(String, Int64)

Adds a Range header to a request for a specific range from the beginning or end of the requested data.

AddRange(String, Int32, Int32)


AddRange(String, Int32, Int32)

Adds a range header to a request for a specified range.

AddRange(String, Int64, Int64)


AddRange(String, Int64, Int64)

Adds a range header to a request for a specified range.

BeginGetRequestStream(AsyncCallback, Object)
BeginGetRequestStream(AsyncCallback, Object)

Begins an asynchronous request for a Stream object to use to write data.

BeginGetResponse(AsyncCallback, Object)
BeginGetResponse(AsyncCallback, Object)

Begins an asynchronous request to an Internet resource.

EndGetRequestStream(IAsyncResult, TransportContext)
EndGetRequestStream(IAsyncResult, TransportContext)

Ends an asynchronous request for a Stream object to use to write data and outputs the TransportContext
associated with the stream.
EndGetRequestStream(IAsyncResult)
EndGetRequestStream(IAsyncResult)

Ends an asynchronous request for a Stream object to use to write data.

EndGetResponse(IAsyncResult)
EndGetResponse(IAsyncResult)

Ends an asynchronous request to an Internet resource.

GetHashCode()
GetHashCode()

Returns a hash value for a WebRequest instance.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data required to serialize the target object.

GetRequestStream()
GetRequestStream()

Gets a Stream object to use to write request data.

GetRequestStream(TransportContext)
GetRequestStream(TransportContext)

Gets a Stream object to use to write request data and outputs the TransportContext associated with the stream.

GetResponse()
GetResponse()

Returns a response from an Internet resource.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

See Also
HttpWebRequest.Abort HttpWebRequest.Abort
I n this Article
Cancels a request to an Internet resource.
public override void Abort ();
override this.Abort : unit -> unit

Examples
In the case of asynchronous requests, it is the responsibility of the client application to implement its own time-out
mechanism. The following code example shows how to do this.
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the State of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] BufferRead;
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
streamResponse = null;
}
}

class HttpWebRequest_BeginGetResponse
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout

// Abort the request if the timer fires.


private static void TimeoutCallback(object state, bool timedOut) {
if (timedOut) {
HttpWebRequest request = state as HttpWebRequest;
if (request != null) {
request.Abort();
}
}
}

static void Main()


{

try
{
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");
/**
* If you are behind a firewall and you do not have your browser proxy setup
* you need to use the following proxy creation code.

// Create a proxy object.


WebProxy myProxy = new WebProxy();

// Associate a new Uri object to the _wProxy object, using the proxy address
// selected by the user.
myProxy.Address = new Uri("http://myproxy");

// Finally, initialize the Web request object proxy property with the _wProxy
// object.
myHttpWebRequest.Proxy=myProxy;
***/

// Create an instance of the RequestState and assign the previous myHttpWebRequest


// object to its request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest;

// Start the asynchronous request.


IAsyncResult result=
(IAsyncResult) myHttpWebRequest.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestState);

// this line implements the timeout, if there is a timeout, the callback fires and the request
becomes aborted
ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new
WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();

// Release the HttpWebResponse resource.


myRequestState.response.Close();
}
catch(WebException e)
{
Console.WriteLine("
Main Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
Console.WriteLine("Press any key to continue..........");
}
catch(Exception e)
{
Console.WriteLine("
Main Exception raised!");
Console.WriteLine("Source :{0} " , e.Source);
Console.WriteLine("Message :{0} " , e.Message);
Console.WriteLine("Press any key to continue..........");
Console.Read();
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
{
// State of request is asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
HttpWebRequest myHttpWebRequest=myRequestState.request;
myRequestState.response = (HttpWebResponse)
myHttpWebRequest.EndGetResponse(asynchronousResult);

// Read the response into a Stream object.


Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.streamResponse=responseStream;

// Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
catch(WebException e)
{
Console.WriteLine("
RespCallback Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
}
allDone.Set();
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{

RequestState myRequestState = (RequestState)asyncResult.AsyncState;


Stream responseStream = myRequestState.streamResponse;
int read = responseStream.EndRead( asyncResult );
// Read the HTML page and then print it to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0,
read));
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
else
{
Console.WriteLine("
The contents of the Html page are : ");
if(myRequestState.requestData.Length>1)
{
string stringContent;
stringContent = myRequestState.requestData.ToString();
Console.WriteLine(stringContent);
}
Console.WriteLine("Press any key to continue..........");
Console.ReadLine();

responseStream.Close();
}

}
catch(WebException e)
{
Console.WriteLine("
ReadCallBack Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
}
allDone.Set();

Remarks
The Abort method cancels a request to a resource. After a request is canceled, calling the GetResponse,
BeginGetResponse, EndGetResponse, GetRequestStream, BeginGetRequestStream, or EndGetRequestStream method
causes a WebException with the Status property set to RequestCanceled.
The Abort method will synchronously execute the callback specified to the BeginGetRequestStream or
BeginGetResponse methods if the Abort method is called while either of these operations are outstanding. This can
lead to potential deadlock issues.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing.
HttpWebRequest.Accept HttpWebRequest.Accept
I n this Article
Gets or sets the value of the Accept HTTP header.

public string Accept { get; set; }


member this.Accept : string with get, set

Returns
String String
The value of the Accept HTTP header. The default value is null .

Examples
The following code example sets the Accept property.
// Create a 'HttpWebRequest' object.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(myUri);
// Set the 'Accept' property to accept an image of any type.
myHttpWebRequest.Accept="image/*";
// The response object of 'HttpWebRequest' is assigned to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

Remarks
To clear the Accept HTTP header, set the Accept property to null .
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.AddRange HttpWebRequest.AddRange
I n this Article

Overloads
AddRange(Int32) AddRange(Int32)
Adds a byte range header to a request for a specific range
from the beginning or end of the requested data.

AddRange(Int64) AddRange(Int64)
Adds a byte range header to a request for a specific range
from the beginning or end of the requested data.

AddRange(Int32, Int32) AddRange(Int32, Int32)


Adds a byte range header to the request for a specified range.

AddRange(Int64, Int64) AddRange(Int64, Int64)


Adds a byte range header to the request for a specified range.

AddRange(String, Int32) AddRange(String, Int32)


Adds a Range header to a request for a specific range from the
beginning or end of the requested data.

AddRange(String, Int64) AddRange(String, Int64)


Adds a Range header to a request for a specific range from the
beginning or end of the requested data.

AddRange(String, Int32, Int32) AddRange(String, Int32, Int32)


Adds a range header to a request for a specified range.

AddRange(String, Int64, Int64) AddRange(String, Int64, Int64)


Adds a range header to a request for a specified range.

Remarks
Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.

AddRange(Int32) AddRange(Int32)
Adds a byte range header to a request for a specific range from the beginning or end of the requested data.
public void AddRange (int range);
member this.AddRange : int -> unit

Parameters
range Int32 Int32
The starting or ending point of the range.
Exceptions
ArgumentException ArgumentException
rangeSpecifier is invalid.
InvalidOperationException InvalidOperationException
The range header could not be added.
Examples
The following code example adds a range header to the request.
// Create a New 'HttpWebRequest' object .
HttpWebRequest myHttpWebRequest1=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest1.AddRange(1000);
Console.WriteLine("Call AddRange(1000)");
Console.Write("Resulting Headers: ");
Console.WriteLine(myHttpWebRequest1.Headers.ToString());

// Create a New 'HttpWebRequest' object .


HttpWebRequest myHttpWebRequest2=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest2.AddRange(-1000);
Console.WriteLine("Call AddRange(-1000)");
Console.Write("Resulting Headers: ");
Console.WriteLine(myHttpWebRequest2.Headers.ToString());

Remarks
The HttpWebRequest.AddRange method adds a byte range header to the request.
If range is positive, the range parameter specifies the starting point of the range. The server should start sending data
from the range parameter specified to the end of the data in the HTTP entity.

If range is negative, the range parameter specifies the ending point of the range. The server should start sending data
from the start of the data in the HTTP entity to the range parameter specified.

Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
An example of a Range header in an HTTP protocol request that requests the server send the first 100 bytes (from the
start to byte position 99) would be the following:
Range: bytes=0-99\r\n\r\n

For this example, the range parameter would be -99.


A HTTP server indicates support for Range headers with the Accept-Ranges header. An example of the Accept-Ranges
header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(Int64) AddRange(Int64)
Adds a byte range header to a request for a specific range from the beginning or end of the requested data.

public void AddRange (long range);


member this.AddRange : int64 -> unit

Parameters
range Int64 Int64
The starting or ending point of the range.
Exceptions
ArgumentException ArgumentException
rangeSpecifier is invalid.
InvalidOperationException InvalidOperationException
The range header could not be added.
Remarks
The HttpWebRequest.AddRange method adds a byte range header to the request.
If range is positive, the range parameter specifies the starting point of the range. The server should start sending data
from the range parameter specified to the end of the data in the HTTP entity.

If range is negative, the range parameter specifies the ending point of the range. The server should start sending data
from the start of the data in the HTTP entity to the range parameter specified.

Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
An example of a Range header in an HTTP protocol request that requests the server send the first 100 bytes (from the
start to byte position 99) would be the following:
Range: bytes=0-99\r\n\r\n

For this example, the range parameter would be -99.

A HTTP server indicates support for Range headers with the Accept-Ranges header. An example of the Accept-Ranges
header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n
If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(Int32, Int32) AddRange(Int32, Int32)


Adds a byte range header to the request for a specified range.
public void AddRange (int from, int to);
member this.AddRange : int * int -> unit

Parameters
from Int32 Int32
The position at which to start sending data.
to Int32 Int32
The position at which to stop sending data.
Exceptions
ArgumentException ArgumentException
rangeSpecifier is invalid.

ArgumentOutOfRangeException ArgumentOutOfRangeException
from is greater than to
-or-
from or to is less than 0.

InvalidOperationException InvalidOperationException
The range header could not be added.
Examples
The following code example adds a range header to the request.
// Create a New 'HttpWebRequest' object .
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.AddRange(50,150);
Console.WriteLine("Call AddRange(50,150)");
Console.Write("Resulting Request Headers: ");
Console.WriteLine(myHttpWebRequest.Headers.ToString());

// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.


HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

// Displays the headers in the response received


Console.Write("Resulting Response Headers: ");
Console.WriteLine(myHttpWebResponse.Headers.ToString());

// Display the contents of the page to the console.


Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuffer = new Char[256];
int count = streamRead.Read( readBuffer, 0, 256 );
Console.WriteLine("
The HTML contents of the page from 50th to 150 characters are :
");
while (count > 0)
{
String outputData = new String(readBuffer, 0, count);
Console.WriteLine(outputData);
count = streamRead.Read(readBuffer, 0, 256);
}
// Release the response object resources.
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();

Remarks
The HttpWebRequest.AddRange method adds a byte range header to the request.
Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
An example of a Range header in an HTTP protocol request that requests the first 100 bytes would be would be the
following:
Range: bytes=0-99\r\n\r\n

For this example, the from parameter would be specified as 0 and the to parameter would be specified as 99. The
range specifier is automatically set as "bytes" by this method.
A HTTP server indicates support for Range headers with the Accept-Ranges header. An example of the Accept-Ranges
header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n
When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(Int64, Int64) AddRange(Int64, Int64)


Adds a byte range header to the request for a specified range.

public void AddRange (long from, long to);


member this.AddRange : int64 * int64 -> unit

Parameters
from Int64 Int64
The position at which to start sending data.
to Int64 Int64
The position at which to stop sending data.
Exceptions
ArgumentException ArgumentException
rangeSpecifier is invalid.

ArgumentOutOfRangeException ArgumentOutOfRangeException
from is greater than to
-or-
from or to is less than 0.

InvalidOperationException InvalidOperationException
The range header could not be added.
Remarks
The HttpWebRequest.AddRange method adds a byte range header to the request.
Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
An example of a Range header in an HTTP protocol request that requests the first 100 bytes would be would be the
following:
Range: bytes=0-99\r\n\r\n

For this example, the from parameter would be specified as 0 and the to parameter would be specified as 99. The
range specifier is automatically set as "bytes" by this method.
A HTTP server indicates support for Range headers with the Accept-Ranges header. An example of the Accept-Ranges
header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(String, Int32) AddRange(String, Int32)


Adds a Range header to a request for a specific range from the beginning or end of the requested data.

public void AddRange (string rangeSpecifier, int range);


member this.AddRange : string * int -> unit

Parameters
rangeSpecifier String String
The description of the range.
range Int32 Int32
The starting or ending point of the range.
Exceptions
ArgumentNullException ArgumentNullException
rangeSpecifier is null .

ArgumentException ArgumentException
rangeSpecifier is invalid.

InvalidOperationException InvalidOperationException
The range header could not be added.
Remarks
The HttpWebRequest.AddRange method adds a Range header to the request.
If range is positive, the range parameter specifies the starting point of the range. The server should start sending data
from the range parameter specified to the end of the data in the HTTP entity.
If range is negative, the range parameter specifies the ending point of the range. The server should start sending data
from the start of the data in the HTTP entity to the range parameter specified.
Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
The rangeSpecifier parameter would normally be specified as a "bytes", since this is the only range specifier
recognized by most HTTP servers. Setting the rangeSpecifier parameter to some other string allows support for
custom range specifiers other than bytes (the byte-range specifier defined in RFC 2616 by the IETF ).
An example of a Range header in an HTTP protocol request that requests the first 100 bytes would be would be the
following:
Range: bytes=-99\r\n\r\n

For this example, the rangeSpecifier parameter would be specified as "bytes" and the range parameter would be -
99.
A HTTP server indicates support for Range headers with the Accept-Ranges header in the response. An example of the
Accept-Ranges header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(String, Int64) AddRange(String, Int64)


Adds a Range header to a request for a specific range from the beginning or end of the requested data.

public void AddRange (string rangeSpecifier, long range);


member this.AddRange : string * int64 -> unit

Parameters
rangeSpecifier String String
The description of the range.
range Int64 Int64
The starting or ending point of the range.
Exceptions
ArgumentNullException ArgumentNullException
rangeSpecifier is null .

ArgumentException ArgumentException
rangeSpecifier is invalid.
InvalidOperationException InvalidOperationException
The range header could not be added.
Remarks
The HttpWebRequest.AddRange method adds a Range header to the request.
If range is positive, the range parameter specifies the starting point of the range. The server should start sending data
from the range parameter specified to the end of the data in the HTTP entity.

If range is negative, the range parameter specifies the ending point of the range. The server should start sending data
from the start of the data in the HTTP entity to the range parameter specified.

Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
The rangeSpecifier parameter would normally be specified as a "bytes", since this is the only range specifier
recognized by most HTTP servers. Setting the rangeSpecifier parameter to some other string allows support for
custom range specifiers other than bytes (the byte-range specifier defined in RFC 2616 by the IETF ).
An example of a Range header in an HTTP protocol request that requests the first 100 bytes would be would be the
following:
Range: bytes=-99\r\n\r\n

For this example, the rangeSpecifier parameter would be specified as "bytes" and the range parameter would be -
99.
A HTTP server indicates support for Range headers with the Accept-Ranges header in the response. An example of the
Accept-Ranges header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(String, Int32, Int32) AddRange(String, Int32, Int32)


Adds a range header to a request for a specified range.

public void AddRange (string rangeSpecifier, int from, int to);


member this.AddRange : string * int * int -> unit

Parameters
rangeSpecifier String String
The description of the range.
from Int32 Int32
The position at which to start sending data.
to Int32 Int32
The position at which to stop sending data.
Exceptions
ArgumentNullException ArgumentNullException
rangeSpecifier is null .

ArgumentOutOfRangeException ArgumentOutOfRangeException
from is greater than to
-or-
from or to is less than 0.
ArgumentException ArgumentException
rangeSpecifier is invalid.
InvalidOperationException InvalidOperationException
The range header could not be added.
Remarks
The HttpWebRequest.AddRange method adds a Range header to the request.
Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
The rangeSpecifier parameter would normally be specified as a "bytes", since this is the only range specifier
recognized by most HTTP servers. Setting the rangeSpecifier parameter to some other string allows support for
custom range specifiers other than bytes (the byte-range specifier defined in RFC 2616 by the IETF ).
An example of a Range header in an HTTP protocol request that requests the first 100 bytes would be would be the
following:
Range: bytes=0-99\r\n\r\n

For this example, the rangeSpecifier parameter would be specified as a "bytes", the from parameter would be 0, and
the to parameter would be 99.

A HTTP server indicates support for Range headers with the Accept-Ranges header in the response. An example of the
Accept-Ranges header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

The string specified in the Accept-Ranges header is the range-specifier that would be by specified in the
rangeSpecifier parameter for this method.

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also

AddRange(String, Int64, Int64) AddRange(String, Int64, Int64)


Adds a range header to a request for a specified range.

public void AddRange (string rangeSpecifier, long from, long to);


member this.AddRange : string * int64 * int64 -> unit

Parameters
rangeSpecifier String String
The description of the range.
from Int64 Int64
The position at which to start sending data.
to Int64 Int64
The position at which to stop sending data.
Exceptions
ArgumentNullException ArgumentNullException
rangeSpecifier is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
from is greater than to
-or-
from or to is less than 0.
ArgumentException ArgumentException
rangeSpecifier is invalid.
InvalidOperationException InvalidOperationException
The range header could not be added.
Remarks
The HttpWebRequest.AddRange method adds a Range header to the request.
Since all HTTP entities are represented in HTTP messages as sequences of bytes, the concept of a byte range is
meaningful for any HTTP entity. However, not all clients and servers need to support byte-range operations.
The Range header on a request allows a client to request that it only wants to receive some part of the specified range
of bytes in an HTTP entity. Servers are not required to support Range header requests.
The rangeSpecifier parameter would normally be specified as a "bytes", since this is the only range specifier
recognized by most HTTP servers. Setting the rangeSpecifier parameter to some other string allows support for
custom range specifiers other than bytes (the byte-range specifier defined in RFC 2616 by the IETF ).
An example of a Range header in an HTTP protocol request that requests the first 100 bytes would be would be the
following:
Range: bytes=0-99\r\n\r\n

For this example, the rangeSpecifier parameter would be specified as a "bytes", the from parameter would be 0, and
the to parameter would be 99.

A HTTP server indicates support for Range headers with the Accept-Ranges header in the response. An example of the
Accept-Ranges header from a server that supports byte-ranges would be as follows:
Accept-Ranges: bytes\r\n\r\n

The string specified in the Accept-Ranges header is the range-specifier that would be by specified in the
rangeSpecifier parameter for this method.

If an Accept-Ranges header is not received in the header of the response from the server, then the server does not
support Range headers. An example of the Accept-Ranges header from a server that does not support ranges, but
recognizes the Accept-Ranges header, would be as follows:
Accept-Ranges: none\r\n\r\n

When receiving the response from a range request, only the HTTP headers associated with the entire request are
parsed and made available via properties on the HttpWebResponse class. Headers associated with each range are
returned in the response.
See AddRangeAddRange
Also
HttpWebRequest.Address HttpWebRequest.Address
I n this Article
Gets the Uniform Resource Identifier (URI) of the Internet resource that actually responds to the request.
public Uri Address { get; }
member this.Address : Uri

Returns
Uri Uri
A Uri that identifies the Internet resource that actually responds to the request. The default is the URI used by the
Create(String) method to initialize the request.

Examples
The following code example checks to see if the HttpWebRequest object req was redirected to another location to
fulfill the request, and sets the value of the hasChanged variable to true if the request was redirected; otherwise
hasChanged is set to false .

bool hasChanged = (req.RequestUri != req.Address);

Remarks
The Address property is set to the URI after any redirections that happen during the request are complete.
The URI of the original request is kept in the RequestUri property.
HttpWebRequest.AllowAutoRedirect HttpWebRequest.
AllowAutoRedirect
I n this Article
Gets or sets a value that indicates whether the request should follow redirection responses.

public virtual bool AllowAutoRedirect { get; set; }


member this.AllowAutoRedirect : bool with get, set

Returns
Boolean Boolean
true if the request should automatically follow redirection responses from the Internet resource; otherwise, false .
The default value is true .

Examples
The following code example uses the AllowAutoRedirect property to allow the request to follow redirection responses.
// Create a new HttpWebRequest Object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.MaximumAutomaticRedirections=1;
myHttpWebRequest.AllowAutoRedirect=true;
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

Remarks
Set AllowAutoRedirect to true if you want the request to automatically follow HTTP redirection headers to the new
location of the resource. The maximum number of redirections to follow is set by the MaximumAutomaticRedirections
property.
If AllowAutoRedirect is set to false , all responses with an HTTP status code from 300 to 399 is returned to the
application.
The Authorization header is cleared on auto-redirects and HttpWebRequest automatically tries to re-authenticate to the
redirected location. In practice, this means that an application can't put custom authentication information into the
Authorization header if it is possible to encounter redirection. Instead, the application must implement and register a
custom authentication module. The System.Net.AuthenticationManager and related class are used to implement a
custom authentication module. The AuthenticationManager.Register method registers a custom authentication
module.
HttpWebRequest.AllowReadStreamBuffering HttpWeb
Request.AllowReadStreamBuffering
I n this Article
Gets or sets a value that indicates whether to buffer the received from the Internet resource.

public virtual bool AllowReadStreamBuffering { get; set; }


member this.AllowReadStreamBuffering : bool with get, set

Returns
Boolean Boolean
true to enable buffering of the data received from the Internet resource; false to disable buffering. The default is
false .
HttpWebRequest.AllowWriteStreamBuffering HttpWeb
Request.AllowWriteStreamBuffering
I n this Article
Gets or sets a value that indicates whether to buffer the data sent to the Internet resource.

public virtual bool AllowWriteStreamBuffering { get; set; }


member this.AllowWriteStreamBuffering : bool with get, set

Returns
Boolean Boolean
true to enable buffering of the data sent to the Internet resource; false to disable buffering. The default is true .

Examples
The following code example uses the AllowWriteStreamBuffering property to disable data buffering.

// Create a new 'HttpWebRequest' object to the mentioned Uri.


HttpWebRequest myHttpWebRequest=
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/codesnippets/next.asp");
// Set AllowWriteStreamBuffering to 'false'.
myHttpWebRequest.AllowWriteStreamBuffering=false;
Console.WriteLine("
Please Enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) uri:");
string inputData =Console.ReadLine();
string postData="firstone="+inputData;
// Set 'Method' property of 'HttpWebRequest' class to POST.
myHttpWebRequest.Method="POST";
ASCIIEncoding encodedData=new ASCIIEncoding();
byte[] byteArray=encodedData.GetBytes(postData);
// Set 'ContentType' property of the 'HttpWebRequest' class to "application/x-www-form-urlencoded".
myHttpWebRequest.ContentType="application/x-www-form-urlencoded";
// If the AllowWriteStreamBuffering property of HttpWebRequest is set to false,the contentlength has
to be set to length of data to be posted else Exception(411) is raised.
myHttpWebRequest.ContentLength=byteArray.Length;
Stream newStream=myHttpWebRequest.GetRequestStream();
newStream.Write(byteArray,0,byteArray.Length);
newStream.Close();
Console.WriteLine("
Data has been posted to the Uri

Please wait for the response..........");


// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

Remarks
When AllowWriteStreamBuffering is true , the data is buffered in memory so it is ready to be resent in the event of
redirections or authentication requests.
HttpWebRequest.AutomaticDecompression HttpWeb
Request.AutomaticDecompression
I n this Article
Gets or sets the type of decompression that is used.

public System.Net.DecompressionMethods AutomaticDecompression { get; set; }


member this.AutomaticDecompression : System.Net.DecompressionMethods with get, set

Returns
DecompressionMethods DecompressionMethods
A DecompressionMethods object that indicates the type of decompression that is used.
Exceptions
InvalidOperationException InvalidOperationException
The object's current state does not allow this property to be set.
HttpWebRequest.BeginGetRequestStream HttpWeb
Request.BeginGetRequestStream
I n this Article
Begins an asynchronous request for a Stream object to use to write data.

public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state);


override this.BeginGetRequestStream : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
The AsyncCallback delegate.
state Object Object
The state object for this request.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that references the asynchronous request.
Exceptions
ProtocolViolationException ProtocolViolationException
The Method property is GET or HEAD.
-or-
KeepAlive is true , AllowWriteStreamBuffering is false , ContentLength is -1, SendChunked is false , and Method is
POST or PUT.
InvalidOperationException InvalidOperationException
The stream is being used by a previous call to BeginGetRequestStream(AsyncCallback, Object)
-or-
TransferEncoding is set to a value and SendChunked is false .
-or-
The thread pool is running out of threads.
NotSupportedException NotSupportedException
The request cache validator indicated that the response for this request can be served from the cache; however,
requests that write data must not use the cache. This exception can occur if you are using a custom cache validator that
is incorrectly implemented.
WebException WebException
Abort() was previously called.
ObjectDisposedException ObjectDisposedException
In a .NET Compact Framework application, a request stream with zero content length was not obtained and closed
correctly. For more information about handling zero content length requests, see Network Programming in the .NET
Compact Framework.

Examples
The following code example uses the BeginGetRequestStream method to make an asynchronous request for a stream
instance.

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

class HttpWebRequestBeginGetRequest
{
private static ManualResetEvent allDone = new ManualResetEvent(false);

public static void Main(string[] args)


{

// Create a new HttpWebRequest object.


HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx");

request.ContentType = "application/x-www-form-urlencoded";

// Set the Method property to 'POST' to post data to the URI.


request.Method = "POST";

// start the asynchronous operation


request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

// Keep the main thread from continuing while the asynchronous


// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}

private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)


{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

// End the operation


Stream postStream = request.EndGetRequestStream(asynchronousResult);

Console.WriteLine("Please enter the input data to be posted:");


string postData = Console.ReadLine();

// Convert the string into a byte array.


byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Write to the request stream.


postStream.Write(byteArray, 0, postData.Length);
postStream.Close();

// Start the asynchronous operation to get the response


request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

private static void GetResponseCallback(IAsyncResult asynchronousResult)


{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

// End the operation


HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();

// Release the HttpWebResponse


response.Close();
allDone.Set();
}
}

Remarks
The BeginGetRequestStream method starts an asynchronous request for a stream used to send data for the
HttpWebRequest. The asynchronous callback method uses the EndGetRequestStream method to return the actual
stream.
The BeginGetRequestStream method requires some synchronous setup tasks to complete (DNS resolution, proxy
detection, and TCP socket connection, for example) before this method becomes asynchronous. As a result, this
method should never be called on a user interface (UI) thread because it might take considerable time (up to several
minutes depending on network settings) to complete the initial synchronous setup tasks before an exception for an
error is thrown or the method succeeds.
To learn more about the thread pool, see The managed thread pool.
Note

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the
BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See DefaultProxy Element (Network Settings)
Also
HttpWebRequest.BeginGetResponse HttpWebRequest.
BeginGetResponse
I n this Article
Begins an asynchronous request to an Internet resource.

public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state);


override this.BeginGetResponse : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
The AsyncCallback delegate
state Object Object
The state object for this request.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that references the asynchronous request for a response.
Exceptions
InvalidOperationException InvalidOperationException
The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object)
-or-
TransferEncoding is set to a value and SendChunked is false .
-or-
The thread pool is running out of threads.
ProtocolViolationException ProtocolViolationException
Method is GET or HEAD, and either ContentLength is greater than zero or SendChunked is true .
-or-
KeepAlive is true , AllowWriteStreamBuffering is false , and either ContentLength is -1, SendChunked is false and
Method is POST or PUT.
-or-
The HttpWebRequest has an entity body but the BeginGetResponse(AsyncCallback, Object) method is called without
calling the BeginGetRequestStream(AsyncCallback, Object) method.
-or-
The ContentLength is greater than zero, but the application does not write all of the promised data.
WebException WebException
Abort() was previously called.
Examples
The following code example uses the BeginGetResponse method to make an asynchronous request for an Internet
resource.
Note

In the case of asynchronous requests, it is the responsibility of the client application to implement its own time-out
mechanism. The following code example shows how to do it.
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the State of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] BufferRead;
public HttpWebRequest request;
public HttpWebResponse response;
public Stream streamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
streamResponse = null;
}
}

class HttpWebRequest_BeginGetResponse
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout

// Abort the request if the timer fires.


private static void TimeoutCallback(object state, bool timedOut) {
if (timedOut) {
HttpWebRequest request = state as HttpWebRequest;
if (request != null) {
request.Abort();
}
}
}

static void Main()


{

try
{
// Create a HttpWebrequest object to the desired URL.
HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");

/**
* If you are behind a firewall and you do not have your browser proxy setup
* you need to use the following proxy creation code.

// Create a proxy object.


// Create a proxy object.
WebProxy myProxy = new WebProxy();

// Associate a new Uri object to the _wProxy object, using the proxy address
// selected by the user.
myProxy.Address = new Uri("http://myproxy");

// Finally, initialize the Web request object proxy property with the _wProxy
// object.
myHttpWebRequest.Proxy=myProxy;
***/

// Create an instance of the RequestState and assign the previous myHttpWebRequest


// object to its request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest;

// Start the asynchronous request.


IAsyncResult result=
(IAsyncResult) myHttpWebRequest.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestState);

// this line implements the timeout, if there is a timeout, the callback fires and the request
becomes aborted
ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new
WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

// The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne();

// Release the HttpWebResponse resource.


myRequestState.response.Close();
}
catch(WebException e)
{
Console.WriteLine("
Main Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
Console.WriteLine("Press any key to continue..........");
}
catch(Exception e)
{
Console.WriteLine("
Main Exception raised!");
Console.WriteLine("Source :{0} " , e.Source);
Console.WriteLine("Message :{0} " , e.Message);
Console.WriteLine("Press any key to continue..........");
Console.Read();
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// State of request is asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
HttpWebRequest myHttpWebRequest=myRequestState.request;
myRequestState.response = (HttpWebResponse)
myHttpWebRequest.EndGetResponse(asynchronousResult);
// Read the response into a Stream object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.streamResponse=responseStream;

// Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
catch(WebException e)
{
Console.WriteLine("
RespCallback Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
}
allDone.Set();
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{

RequestState myRequestState = (RequestState)asyncResult.AsyncState;


Stream responseStream = myRequestState.streamResponse;
int read = responseStream.EndRead( asyncResult );
// Read the HTML page and then print it to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0,
read));
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
return;
}
else
{
Console.WriteLine("
The contents of the Html page are : ");
if(myRequestState.requestData.Length>1)
{
string stringContent;
stringContent = myRequestState.requestData.ToString();
Console.WriteLine(stringContent);
}
Console.WriteLine("Press any key to continue..........");
Console.ReadLine();

responseStream.Close();
}

}
catch(WebException e)
{
Console.WriteLine("
ReadCallBack Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
}
allDone.Set();

}
}

Remarks
The BeginGetResponse method starts an asynchronous request for a response from the Internet resource. The
asynchronous callback method uses the EndGetResponse method to return the actual WebResponse.
A ProtocolViolationException is thrown in several cases when the properties set on the HttpWebRequest class are
conflicting. This exception occurs if an application sets the ContentLength property and the SendChunked property to
true , and then sends an HTTP GET request. This exception occurs if an application tries to send chunked to a server
that only supports HTTP 1.0 protocol, where this is not supported. This exception occurs if an application tries to send
data without setting the ContentLength property or the SendChunked is false when buffering is disabled and on a
keepalive connection (the KeepAlive property is true ) .

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from
the server.
The BeginGetResponse method requires some synchronous setup tasks to complete (DNS resolution, proxy detection,
and TCP socket connection, for example) before this method becomes asynchronous. As a result, this method should
never be called on a user interface (UI) thread because it might take considerable time (up to several minutes
depending on network settings) to complete the initial synchronous setup tasks before an exception for an error is
thrown or the method succeeds.
To learn more about the thread pool, see The managed thread pool.
Note

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the
BeginGetRequestStream method, you must use the BeginGetResponse method to retrieve the response.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See DefaultProxy Element (Network Settings)
Also
HttpWebRequest.ClientCertificates HttpWebRequest.
ClientCertificates
I n this Article
Gets or sets the collection of security certificates that are associated with this request.

public System.Security.Cryptography.X509Certificates.X509CertificateCollection ClientCertificates {


get; set; }
member this.ClientCertificates :
System.Security.Cryptography.X509Certificates.X509CertificateCollection with get, set

Returns
X509CertificateCollection X509CertificateCollection
The X509CertificateCollection that contains the security certificates associated with this request.
Exceptions
ArgumentNullException ArgumentNullException
The value specified for a set operation is null .

Remarks
An application can add a certificate to a collection, but might not have access rights to it. To use a certificate contained
in the collection, the application must have the same access rights as the entity that issued the certificate.
Note

The Framework caches SSL sessions as they are created and attempts to reuse a cached session for a new request, if
possible. When attempting to reuse an SSL session, the Framework uses the first element of ClientCertificates (if there
is one), or tries to reuse an anonymous sessions if ClientCertificates is empty.
Note

For performance reasons, you shouldn't add a client certificate to a HttpWebRequest unless you know the server will
ask for it.
For a code example illustrating how to enumerate the certificates in the client certificate store, see the
X509Certificate2Collection class.
HttpWebRequest.Connection HttpWebRequest.
Connection
I n this Article
Gets or sets the value of the Connection HTTP header.

public string Connection { get; set; }


member this.Connection : string with get, set

Returns
String String
The value of the Connection HTTP header. The default value is null .

Exceptions
ArgumentException ArgumentException
The value of Connection is set to Keep-alive or Close.

Examples
The following code example uses the Connection property to set the value of the Connection HTTP Header.

class HttpWebRequest_Connection
{
static void Main()
{
try
{

// Create a new HttpWebRequest object.Make sure that


// a default proxy is set if you are behind a firewall.
HttpWebRequest myHttpWebRequest1 =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com");

myHttpWebRequest1.KeepAlive=false;
// Assign the response object of HttpWebRequest to a HttpWebResponse variable.
HttpWebResponse myHttpWebResponse1 =
(HttpWebResponse)myHttpWebRequest1.GetResponse();

Console.WriteLine("
The HTTP request Headers for the first request are:
{0}",myHttpWebRequest1.Headers);
Console.WriteLine("Press Enter Key to Continue..........");
Console.Read();

Stream streamResponse=myHttpWebResponse1.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("The contents of the Html page are.......
");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
Console.WriteLine();
Console.WriteLine();
// Close the Stream object.
streamResponse.Close();
streamRead.Close();
// Release the resources held by response object.
myHttpWebResponse1.Close();
// Create a new HttpWebRequest object for the specified Uri.
HttpWebRequest myHttpWebRequest2 =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest2.Connection="Close";
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse2 =
(HttpWebResponse)myHttpWebRequest2.GetResponse();
// Release the resources held by response object.
myHttpWebResponse2.Close();
Console.WriteLine("
The Http RequestHeaders are
{0}",myHttpWebRequest2.Headers);
Console.WriteLine("
Press 'Enter' Key to Continue.........");
Console.Read();
}
catch(ArgumentException e)
{
Console.WriteLine("
The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to
'Close'");
Console.WriteLine("
{0}",e.Message);
}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source :{0} " , e.Source);
Console.WriteLine("Message :{0} " , e.Message);
}
}
}

Remarks
The request sends the Connection property to the Internet resource as the Connection HTTP header. If the value of
the KeepAlive property is true , the value "Keep-alive" is appended to the end of the Connection header.
To clear the Connection HTTP header, set the Connection property to null .

Changing the Connection property after the request has been started by calling the GetRequestStream,
BeginGetRequestStream, GetResponse, or BeginGetResponse method throws an InvalidOperationException.
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.ConnectionGroupName HttpWeb
Request.ConnectionGroupName
I n this Article
Gets or sets the name of the connection group for the request.

public override string ConnectionGroupName { get; set; }


member this.ConnectionGroupName : string with get, set

Returns
String String
The name of the connection group for this request. The default value is null .

Examples
The following code example show how to use user information to form a connection group, assuming that the
variables username , password , and domain are set by the application before this code is called.

// Create a secure group name.


SHA1Managed Sha1 = new SHA1Managed();
Byte[] updHash = Sha1.ComputeHash(Encoding.UTF8.GetBytes("username" + "password" + "domain"));
String secureGroupName = Encoding.Default.GetString(updHash);

// Create a request for a specific URL.


WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");

// Set the authentication credentials for the request.


myWebRequest.Credentials = new NetworkCredential("username", "password", "domain");
myWebRequest.ConnectionGroupName = secureGroupName;

// Get the response.


WebResponse myWebResponse=myWebRequest.GetResponse();

// Insert the code that uses myWebResponse here.

// Close the response.


myWebResponse.Close();

Remarks
The ConnectionGroupName property enables you to associate a request with a connection group. This is useful when
your application makes requests to one server for different users, such as a Web site that retrieves customer
information from a database server.
See Connection Grouping
Also
HttpWebRequest.ContentLength HttpWebRequest.
ContentLength
I n this Article
Gets or sets the Content-length HTTP header.

public override long ContentLength { get; set; }


member this.ContentLength : int64 with get, set

Returns
Int64 Int64
The number of bytes of data to send to the Internet resource. The default is -1, which indicates the property has not
been set and that there is no request data to send.
Exceptions
InvalidOperationException InvalidOperationException
The request has been started by calling the GetRequestStream(), BeginGetRequestStream(AsyncCallback, Object),
GetResponse(), or BeginGetResponse(AsyncCallback, Object) method.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The new ContentLength value is less than 0.

Examples
The following code example sets the ContentLength property to the length of the string being posted.
// Set the 'Method' property of the 'Webrequest' to 'POST'.
myHttpWebRequest.Method = "POST";
Console.WriteLine ("
Please enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri :");

// Create a new string object to POST data to the Url.


string inputData = Console.ReadLine ();

string postData = "firstone=" + inputData;


ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.


myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.


myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);


Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}",
myHttpWebRequest.ContentLength);

// Close the Stream object.


newStream.Close ();
Remarks
The ContentLength property contains the value to send as the Content-length HTTP header with the request.
Any value other than -1 in the ContentLength property indicates that the request uploads data and that only methods
that upload data are allowed to be set in the Method property.
After the ContentLength property is set to a value, that number of bytes must be written to the request stream that is
returned by calling the GetRequestStream method or both the BeginGetRequestStream and the EndGetRequestStream
methods.
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.ContentType HttpWebRequest.Content
Type
I n this Article
Gets or sets the value of the Content-type HTTP header.

public override string ContentType { get; set; }


member this.ContentType : string with get, set

Returns
String String
The value of the Content-type HTTP header. The default value is null .

Examples
The following code example sets the ContentType property.
// Set the 'Method' property of the 'Webrequest' to 'POST'.
myHttpWebRequest.Method = "POST";
Console.WriteLine ("
Please enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri :");

// Create a new string object to POST data to the Url.


string inputData = Console.ReadLine ();

string postData = "firstone=" + inputData;


ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.


myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.


myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);


Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}",
myHttpWebRequest.ContentLength);

// Close the Stream object.


newStream.Close ();

Remarks
The ContentType property contains the media type of the request. Values assigned to the ContentType property
replace any existing contents when the request sends the Content-type HTTP header.
To clear the Content-type HTTP header, set the ContentType property to null .
Note

The value for this property is stored in WebHeaderCollection . If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.ContinueDelegate HttpWebRequest.
ContinueDelegate
I n this Article
Gets or sets the delegate method called when an HTTP 100-continue response is received from the Internet resource.

public System.Net.HttpContinueDelegate ContinueDelegate { get; set; }


member this.ContinueDelegate : System.Net.HttpContinueDelegate with get, set

Returns
HttpContinueDelegate HttpContinueDelegate
A delegate that implements the callback method that executes when an HTTP Continue response is returned from the
Internet resource. The default value is null .

Remarks
The ContinueDelegate property specifies the callback method to call when the client receives a 100-Continue response.
When the ContinueDelegate property is set, the client calls the delegate whenever protocol responses of type
HttpStatusCode.Continue (100) are received. This is useful if you want the client to display the status of the data being
received from the Internet resource.
HttpWebRequest.ContinueTimeout HttpWebRequest.
ContinueTimeout
I n this Article
Gets or sets a timeout, in milliseconds, to wait until the 100-Continue is received from the server.

public int ContinueTimeout { get; set; }


member this.ContinueTimeout : int with get, set

Returns
Int32 Int32
The timeout, in milliseconds, to wait until the 100-Continue is received.

Remarks
If the 100-Continue response is received before the timeout expires, the entity body can be sent.
HttpWebRequest.CookieContainer HttpWebRequest.
CookieContainer
I n this Article
Gets or sets the cookies associated with the request.

public virtual System.Net.CookieContainer CookieContainer { get; set; }


member this.CookieContainer : System.Net.CookieContainer with get, set

Returns
CookieContainer CookieContainer
A CookieContainer that contains the cookies associated with this request.

Examples
The following code example sends a request to a URL and displays the cookies returned in the response.
using System.Net;
using System;
namespace Examples.System.Net.Cookies
{
// This example is run at the command line.
// Specify one argument: the name of the host to
// send the request to.
// If the request is sucessful, the example displays the contents of the cookies
// returned by the host.

public class CookieExample


{
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Specify the URL to receive the request.");
Environment.Exit(1);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}
}
}
}

// Output from this example will be vary depending on the host name specified,
// but will be similar to the following.
/*
Cookie:
CustomerID = 13xyz
Domain: .contoso.com
Path: /
Port:
Secure: False
When issued: 1/14/2003 3:20:57 PM
Expires: 1/17/2013 11:14:07 AM (expired? False)
Don't save: False
Comment:
Uri for comments:
Version: RFC 2965
String: CustomerID = 13xyz
*/

Remarks
The CookieContainer property provides an instance of the CookieContainer class that contains the cookies associated
with this request.
CookieContainer is null by default. You must assign a CookieContainer object to the property to have cookies
returned in the Cookies property of the HttpWebResponse returned by the GetResponse method.
Note

For security reasons, cookies are disabled by default. If you want to use cookies, use the CookieContainer property to
enable cookies.
See CookieContainerCookieContainer
Also
HttpWebRequest.Credentials HttpWebRequest.
Credentials
I n this Article
Gets or sets authentication information for the request.

public override System.Net.ICredentials Credentials { get; set; }


member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials that contains the authentication credentials associated with the request. The default is null .

Examples
The following code example sets the credentials for a request.
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test


{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

// Set some reasonable limits on resources used by this request


request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Console.WriteLine ("Content length is {0}", response.ContentLength);


Console.WriteLine ("Content type is {0}", response.ContentType);

// Get the stream associated with the response.


Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");


Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542


Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Remarks
The Credentials property contains authentication information to identify the maker of the request. The Credentials
property can be either a NetworkCredential, in which case the user, password, and domain information contained in
the NetworkCredential object is used to authenticate the request, or it can be a CredentialCache, in which case the
Uniform Resource Identifier (URI) of the request is used to determine the user, password, and domain information to
use to authenticate the request.
In most client scenarios, you should use the DefaultCredentials property, which contains the credentials of the currently
logged on user. To do this, set the UseDefaultCredentials property to true instead of setting this property.

If the HttpWebRequest class is being used in a middle-tier application, such as an ASP.NET application, the credentials
in the DefaultCredentials property belong to the account running the ASP page (the server-side credentials). Typically,
you would set this property to the credentials of the client on whose behalf the request is made.
Note

The NTLM authentication scheme cannot be used to impersonate another user. Kerberos must be specially configured
to support impersonation.
To restrict HttpWebRequest to one or more authentication methods, use the CredentialCache class and bind your
credentials to one or more authentication schemes
Supported authentication schemes include Digest, Negotiate, Kerberos, NTLM, and Basic.
For security reasons, when automatically following redirects, store the credentials that you want to be included in the
redirect in a CredentialCache and assign it to this property. This property will automatically be set to null upon
redirection if it contains anything except a CredentialCache. Having this property value be automatically set to null
under those conditions prevents credentials from being sent to any unintended destination.
HttpWebRequest.Date HttpWebRequest.Date
I n this Article
Gets or sets the Date HTTP header value to use in an HTTP request.

public DateTime Date { get; set; }


member this.Date : DateTime with get, set

Returns
DateTime DateTime
The Date header value in the HTTP request.

Remarks
If the Date header is null , then the return value will be set to DateTime.MinValue.
The Date property is a standard System.DateTime object and can contain a System.DateTimeKind field of
DateTimeKind.Local, DateTimeKind.Utc, or DateTimeKind.Unspecified. Any kind of time can be set when using the
Date property. If DateTimeKind.Unspecified is set or retrieved, the Date property is assumed to be DateTimeKind.Local
(local time).

The classes in the System.Net namespace always write it out the Date property on the wire during transmission in
standard form using GMT (Utc) format.
If the Date property is set to DateTime.MinValue, then the Date HTTP header is removed from the Headers property
and the WebHeaderCollection.
If the Date property is DateTime.MinValue, this indicates that the Date HTTP header is not included in the Headers
property and the WebHeaderCollection.
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
If the Date is set and an attempt is made to send a HttpWebRequest with no body, then a
System.Net.ProtocolViolationException will be thrown by the BeginGetResponse, GetResponse, and EndGetResponse
methods.
HttpWebRequest.DefaultCachePolicy HttpWebRequest.
DefaultCachePolicy
I n this Article
Gets or sets the default cache policy for this request.

public static System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get; set; }


member this.DefaultCachePolicy : System.Net.Cache.RequestCachePolicy with get, set

Returns
RequestCachePolicy RequestCachePolicy
A HttpRequestCachePolicy that specifies the cache policy in effect for this request when no other policy is applicable.

Remarks
Setting this property registers the specified policy for the HTTP and HTTPS schemes. This policy is used for this
request if:
There is no WebRequest.CachePolicy property specified for this request.
-or-
The machine and application configuration files do not specify a cache policy that is applicable to the Uniform Resource
Identifier (URI) used to create this request.
The cache policy determines whether the requested resource can be taken from a cache instead of sending the request
to the resource host computer.
A copy of a resource is only added to the cache if the response stream for the resource is retrieved and read to the end
of the stream. So another request for the same resource could use a cached copy, depending on the cache policy level
for this request.
See RequestCachePolicyRequestCachePolicy
Also CachePolicyCachePolicy
HttpWebRequest.DefaultMaximumErrorResponseLength
HttpWebRequest.DefaultMaximumErrorResponseLength
I n this Article
Gets or sets the default maximum length of an HTTP error response.

public static int DefaultMaximumErrorResponseLength { get; set; }


member this.DefaultMaximumErrorResponseLength : int with get, set

Returns
Int32 Int32
The default maximum length of an HTTP error response.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value is less than 0 and is not equal to -1.
HttpWebRequest.DefaultMaximumResponseHeaders
Length HttpWebRequest.DefaultMaximumResponse
HeadersLength
I n this Article
Gets or sets the default for the MaximumResponseHeadersLength property.
public static int DefaultMaximumResponseHeadersLength { get; set; }
member this.DefaultMaximumResponseHeadersLength : int with get, set

Returns
Int32 Int32
The length, in kilobytes (1024 bytes), of the default maximum for response headers received. The default configuration
file sets this value to 64 kilobytes.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value is not equal to -1 and is less than zero.

Remarks
The length of the response header received the response status line and any extra control characters that are received
as part of HTTP protocol. A value of -1 means no limit is imposed on the response headers received; a value of 0
means that all requests fail.
This value can also be changed in the configuration file. The impact of this property can be overridden by setting the
MaximumResponseHeadersLength property on an instance of the HttpWebRequest class.
HttpWebRequest.EndGetRequestStream HttpWeb
Request.EndGetRequestStream
I n this Article

Overloads
EndGetRequestStream(IAsyncResult, TransportContext) End
GetRequestStream(IAsyncResult, TransportContext) Ends an asynchronous request for a Stream object to use to
write data and outputs the TransportContext associated with
the stream.

EndGetRequestStream(IAsyncResult) EndGetRequestStream(
IAsyncResult) Ends an asynchronous request for a Stream object to use to
write data.

EndGetRequestStream(IAsyncResult, TransportContext)
EndGetRequestStream(IAsyncResult, TransportContext)
Ends an asynchronous request for a Stream object to use to write data and outputs the TransportContext associated
with the stream.
public System.IO.Stream EndGetRequestStream (IAsyncResult asyncResult, out
System.Net.TransportContext transportContext);
override this.EndGetRequestStream : IAsyncResult * -> System.IO.Stream

Parameters
asyncResult IAsyncResult IAsyncResult
The pending request for a stream.
context TransportContext TransportContext
The TransportContext for the Stream.
Returns
Stream Stream
A Stream to use to write request data.
Exceptions
ArgumentException ArgumentException
asyncResult was not returned by the current instance from a call to BeginGetRequestStream(AsyncCallback, Object).
ArgumentNullException ArgumentNullException
asyncResult is null .
InvalidOperationException InvalidOperationException
This method was called previously using asyncResult .

IOException IOException
The request did not complete, and no stream is available.
WebException WebException
Abort() was previously called.
-or-
An error occurred while processing the request.
Remarks
The EndGetRequestStream method completes an asynchronous request for a stream that was started by the
BeginGetRequestStream method and outputs the TransportContext associated with the stream. After the Stream object
has been returned, you can send data with the HttpWebRequest by using the Stream.Write method.
Some applications that use integrated Windows authentication with extended protection may need to be able to query
the transport layer used by HttpWebRequest in order to retrieve the channel binding token (CBT) from the underlying
TLS channel. The GetRequestStream method provides access to this information for HTTP methods which have a
request body ( POST and PUT requests). This is only needed if the application is implementing its own authentication
and needs access to the CBT.
Note

If an application needs to set the value of the ContentLength property, then this must be done before retrieving the
stream and writing data to it.
Cautio n

You must call the Stream.Close method to close the stream and release the connection for reuse. Failure to close the
stream causes your application to run out of connections.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See TransportContextTransportContext
Also Integrated Windows Authentication with Extended Protection

EndGetRequestStream(IAsyncResult)
EndGetRequestStream(IAsyncResult)
Ends an asynchronous request for a Stream object to use to write data.
public override System.IO.Stream EndGetRequestStream (IAsyncResult asyncResult);
override this.EndGetRequestStream : IAsyncResult -> System.IO.Stream

Parameters
asyncResult IAsyncResult IAsyncResult
The pending request for a stream.
Returns
Stream Stream
A Stream to use to write request data.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .
IOException IOException
The request did not complete, and no stream is available.
ArgumentException ArgumentException
asyncResult was not returned by the current instance from a call to BeginGetRequestStream(AsyncCallback, Object).

InvalidOperationException InvalidOperationException
This method was called previously using asyncResult .

WebException WebException
Abort() was previously called.
-or-
An error occurred while processing the request.
Examples
The following code example uses the EndGetRequestStream method to end an asynchronous request for a stream
instance.

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

class HttpWebRequestBeginGetRequest
{
private static ManualResetEvent allDone = new ManualResetEvent(false);

public static void Main(string[] args)


{

// Create a new HttpWebRequest object.


HttpWebRequest request =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/example.aspx");

request.ContentType = "application/x-www-form-urlencoded";

// Set the Method property to 'POST' to post data to the URI.


request.Method = "POST";

// start the asynchronous operation


request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);

// Keep the main thread from continuing while the asynchronous


// operation completes. A real world application
// could do something useful such as updating its user interface.
allDone.WaitOne();
}

private static void GetRequestStreamCallback(IAsyncResult asynchronousResult)


{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
// End the operation
Stream postStream = request.EndGetRequestStream(asynchronousResult);

Console.WriteLine("Please enter the input data to be posted:");


string postData = Console.ReadLine();

// Convert the string into a byte array.


byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Write to the request stream.


postStream.Write(byteArray, 0, postData.Length);
postStream.Close();

// Start the asynchronous operation to get the response


request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
}

private static void GetResponseCallback(IAsyncResult asynchronousResult)


{
HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;

// End the operation


HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream object
streamResponse.Close();
streamRead.Close();

// Release the HttpWebResponse


response.Close();
allDone.Set();
}
}

Remarks
The EndGetRequestStream method completes an asynchronous request for a stream that was started by the
BeginGetRequestStream method. After the Stream object has been returned, you can send data with the
HttpWebRequest by using the Stream.Write method.
Note

You must set the value of the ContentLength property before writing data to the stream.
Cautio n

You must call the Stream.Close method to close the stream and release the connection for reuse. Failure to close the
stream causes your application to run out of connections.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
HttpWebRequest.EndGetResponse HttpWebRequest.End
GetResponse
I n this Article
Ends an asynchronous request to an Internet resource.

public override System.Net.WebResponse EndGetResponse (IAsyncResult asyncResult);


override this.EndGetResponse : IAsyncResult -> System.Net.WebResponse

Parameters
asyncResult IAsyncResult IAsyncResult
The pending request for a response.
Returns
WebResponse WebResponse
A WebResponse that contains the response from the Internet resource.
Exceptions
ArgumentNullException ArgumentNullException
asyncResult is null .
InvalidOperationException InvalidOperationException
This method was called previously using asyncResult.
-or-
The ContentLength property is greater than 0 but the data has not been written to the request stream.
WebException WebException
Abort() was previously called.
-or-
An error occurred while processing the request.
ArgumentException ArgumentException
asyncResult was not returned by the current instance from a call to BeginGetResponse(AsyncCallback, Object).

Examples
The following code example uses the EndGetResponse method to end an asynchronous request for an Internet
resource.
try
{

// Create a HttpWebrequest object to the desired URL.


HttpWebRequest myHttpWebRequest1= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");

// Create an instance of the RequestState and assign the previous myHttpWebRequest1


// object to it's request field.
// object to it's request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myHttpWebRequest1;

// Start the asynchronous request.


IAsyncResult result=
(IAsyncResult) myHttpWebRequest1.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestState);

allDone.WaitOne();

// Release the HttpWebResponse resource.


myRequestState.response.Close();
}
catch(WebException e)
{
Console.WriteLine("
Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);
Console.WriteLine("Press any key to continue..........");
}
catch(Exception e)
{
Console.WriteLine("
Exception raised!");
Console.WriteLine("Source :{0} " , e.Source);
Console.WriteLine("Message :{0} " , e.Message);
Console.WriteLine("Press any key to continue..........");
Console.Read();
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// State of request is asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
HttpWebRequest myHttpWebRequest2=myRequestState.request;
myRequestState.response = (HttpWebResponse)
myHttpWebRequest2.EndGetResponse(asynchronousResult);

// Read the response into a Stream object.


Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.streamResponse=responseStream;

// Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
}
catch(WebException e)
{
Console.WriteLine("
Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);

}
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{

RequestState myRequestState = (RequestState)asyncResult.AsyncState;


Stream responseStream = myRequestState.streamResponse;
int read = responseStream.EndRead( asyncResult );
// Read the HTML page and then print it to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
}
else
{
Console.WriteLine("
The contents of the Html page are : ");
if(myRequestState.requestData.Length>1)
{
string stringContent;
stringContent = myRequestState.requestData.ToString();
Console.WriteLine(stringContent);
}
Console.WriteLine("Press any key to continue..........");
Console.ReadLine();

responseStream.Close();
allDone.Set();

}
catch(WebException e)
{
Console.WriteLine("
Exception raised!");
Console.WriteLine("
Message:{0}",e.Message);
Console.WriteLine("
Status:{0}",e.Status);

Remarks
The EndGetResponse method completes an asynchronous request for an Internet resource that was started by calling
the BeginGetResponse method.
Cautio n

You must call the Close method to close the stream and release the connection. Failure to do so may cause your
application to run out of connections.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
HttpWebRequest.Expect HttpWebRequest.Expect
I n this Article
Gets or sets the value of the Expect HTTP header.

public string Expect { get; set; }


member this.Expect : string with get, set

Returns
String String
The contents of the Expect HTTP header. The default value is null .
The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
Exceptions
ArgumentException ArgumentException
Expect is set to a string that contains "100-continue" as a substring.
See DefaultProxy Element (Network Settings)
Also
HttpWebRequest.GetHashCode HttpWebRequest.Get
HashCode
I n this Article
Returns a hash value for a WebRequest instance.

public override int GetHashCode ();


override this.GetHashCode : unit -> int

Returns
Int32 Int32
An integer hash value.

Remarks
The GetHashCode method returns a hash code of the web request. This value can be used as a key in hash tables.
HttpWebRequest.GetObjectData HttpWebRequest.Get
ObjectData
I n this Article
Populates a SerializationInfo with the data required to serialize the target object.

[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?


linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
protected override void GetObjectData (System.Runtime.Serialization.SerializationInfo
serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.
Attributes ObsoleteAttribute ObsoleteAttribute

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
HttpWebRequest.GetRequestStream HttpWebRequest.
GetRequestStream
I n this Article

Overloads
GetRequestStream() GetRequestStream()
Gets a Stream object to use to write request data.

GetRequestStream(TransportContext) GetRequestStream(
TransportContext) Gets a Stream object to use to write request data and outputs
the TransportContext associated with the stream.

GetRequestStream() GetRequestStream()
Gets a Stream object to use to write request data.
public override System.IO.Stream GetRequestStream ();
override this.GetRequestStream : unit -> System.IO.Stream

Returns
Stream Stream
A Stream to use to write request data.
Exceptions
ProtocolViolationException ProtocolViolationException
The Method property is GET or HEAD.
-or-
KeepAlive is true , AllowWriteStreamBuffering is false , ContentLength is -1, SendChunked is false , and Method is
POST or PUT.
InvalidOperationException InvalidOperationException
The GetRequestStream() method is called more than once.
-or-
TransferEncoding is set to a value and SendChunked is false .
NotSupportedException NotSupportedException
The request cache validator indicated that the response for this request can be served from the cache; however,
requests that write data must not use the cache. This exception can occur if you are using a custom cache validator that
is incorrectly implemented.
WebException WebException
Abort() was previously called.
-or-
The time-out period for the request expired.
-or-
An error occurred while processing the request.
ObjectDisposedException ObjectDisposedException
In a .NET Compact Framework application, a request stream with zero content length was not obtained and closed
correctly. For more information about handling zero content length requests, see Network Programming in the .NET
Compact Framework.
Examples
The following code example uses the GetRequestStream method to return a stream instance.
// Set the 'Method' property of the 'Webrequest' to 'POST'.
myHttpWebRequest.Method = "POST";
Console.WriteLine ("
Please enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri :");

// Create a new string object to POST data to the Url.


string inputData = Console.ReadLine ();

string postData = "firstone=" + inputData;


ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.


myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.


myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);


Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}",
myHttpWebRequest.ContentLength);

// Close the Stream object.


newStream.Close ();

Remarks
The GetRequestStream method returns a stream to use to send data for the HttpWebRequest. After the Stream object
has been returned, you can send data with the HttpWebRequest by using the Stream.Write method.
If an application needs to set the value of the ContentLength property, then this must be done before retrieving the
stream.
You must call the Stream.Close method to close the stream and release the connection for reuse. Failure to close the
stream causes your application to run out of connections.
Note

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the
GetRequestStream method, you must use the GetResponse method to retrieve the response.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See DefaultProxy Element (Network Settings)
Also

GetRequestStream(TransportContext)
GetRequestStream(TransportContext)
Gets a Stream object to use to write request data and outputs the TransportContext associated with the stream.

public System.IO.Stream GetRequestStream (out System.Net.TransportContext context);


override this.GetRequestStream : -> System.IO.Stream

Parameters
context TransportContext TransportContext
The TransportContext for the Stream.
Returns
Stream Stream
A Stream to use to write request data.
Exceptions
Exception Exception
The GetRequestStream() method was unable to obtain the Stream.
InvalidOperationException InvalidOperationException
The GetRequestStream() method is called more than once.
-or-
TransferEncoding is set to a value and SendChunked is false .

NotSupportedException NotSupportedException
The request cache validator indicated that the response for this request can be served from the cache; however,
requests that write data must not use the cache. This exception can occur if you are using a custom cache validator that
is incorrectly implemented.
ProtocolViolationException ProtocolViolationException
The Method property is GET or HEAD.
-or-
KeepAlive is true , AllowWriteStreamBuffering is false , ContentLength is -1, SendChunked is false , and Method is
POST or PUT.
WebException WebException
Abort() was previously called.
-or-
The time-out period for the request expired.
-or-
An error occurred while processing the request.
Remarks
The GetRequestStream method returns a stream to use to send data for the HttpWebRequest and outputs the
TransportContext associated with the stream. After the Stream object has been returned, you can send data with the
HttpWebRequest by using the Stream.Write method.
Some applications that use integrated Windows authentication with extended protection may need to be able to query
the transport layer used by HttpWebRequest in order to retrieve the channel binding token (CBT) from the underlying
TLS channel. The GetRequestStream method provides access to this information for HTTP methods which have a
request body ( POST and PUT requests). This is only needed if the application is implementing its own authentication
and needs access to the CBT.
If an application needs to set the value of the ContentLength property, then this must be done before retrieving the
stream.
You must call the Stream.Close method to close the stream and release the connection for reuse. Failure to close the
stream causes your application to run out of connections.
Note

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the
GetRequestStream method, you must use the GetResponse method to retrieve the response.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See TransportContextTransportContext
Also Integrated Windows Authentication with Extended Protection
HttpWebRequest.GetResponse HttpWebRequest.Get
Response
I n this Article
Returns a response from an Internet resource.

public override System.Net.WebResponse GetResponse ();


override this.GetResponse : unit -> System.Net.WebResponse

Returns
WebResponse WebResponse
A WebResponse that contains the response from the Internet resource.
Exceptions
InvalidOperationException InvalidOperationException
The stream is already in use by a previous call to BeginGetResponse(AsyncCallback, Object).
-or-
TransferEncoding is set to a value and SendChunked is false .
ProtocolViolationException ProtocolViolationException
Method is GET or HEAD, and either ContentLength is greater or equal to zero or SendChunked is true .
-or-
KeepAlive is true , AllowWriteStreamBuffering is false , ContentLength is -1, SendChunked is false , and Method is
POST or PUT.
-or-
The HttpWebRequest has an entity body but the GetResponse() method is called without calling the
GetRequestStream() method.
-or-
The ContentLength is greater than zero, but the application does not write all of the promised data.
NotSupportedException NotSupportedException
The request cache validator indicated that the response for this request can be served from the cache; however, this
request includes data to be sent to the server. Requests that send data must not use the cache. This exception can occur
if you are using a custom cache validator that is incorrectly implemented.
WebException WebException
Abort() was previously called.
-or-
The time-out period for the request expired.
-or-
An error occurred while processing the request.
Examples
The following code example gets the response for a request.
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test


{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

// Set some reasonable limits on resources used by this request


request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Console.WriteLine ("Content length is {0}", response.ContentLength);


Console.WriteLine ("Content type is {0}", response.ContentType);

// Get the stream associated with the response.


Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");


Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542


Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Remarks
The GetResponse method returns a WebResponse object that contains the response from the Internet resource. The
actual instance returned is an HttpWebResponse, and can be typecast to that class to access HTTP -specific properties.
A ProtocolViolationException is thrown in several cases when the properties set on the HttpWebRequest class are
conflicting. This exception occurs if an application sets the ContentLength property and the SendChunked property to
true , and then sends an HTTP GET request. This exception occurs if an application tries to send chunked to a server
that only supports HTTP 1.0 protocol, where this is not supported. This exception occurs if an application tries to send
data without setting the ContentLength property or the SendChunked is false when buffering is disabled and on a
keepalive connection (the KeepAlive property is true ) .
Cautio n

You must call the Close method to close the stream and release the connection. Failure to do so may cause your
application to run out of connections.
When using the POST method, you must get the request stream, write the data to be posted, and close the stream. This
method blocks waiting for content to post; if there is no time-out set and you do not provide content, the calling thread
blocks indefinitely.
Note

Multiple calls to GetResponse return the same response object; the request is not reissued.
Note

Your application cannot mix synchronous and asynchronous methods for a particular request. If you call the
GetRequestStream method, you must use the GetResponse method to retrieve the response.
Note

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from
the server.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
Note

For security reasons, cookies are disabled by default. If you wish to use cookies, use the CookieContainer property to
enable cookies.
See TimeoutTimeout
Also DefaultProxy Element (Network Settings)
HttpWebRequest.HaveResponse HttpWebRequest.Have
Response
I n this Article
Gets a value that indicates whether a response has been received from an Internet resource.

public virtual bool HaveResponse { get; }


member this.HaveResponse : bool

Returns
Boolean Boolean
true if a response has been received; otherwise, false .

Examples
The following code example checks the HaveResponse property to determine if a response has been received from an
Internet resource.
// Create a new 'HttpWebRequest' Object.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
HttpWebResponse myHttpWebResponse;
// Display the 'HaveResponse' property of the 'HttpWebRequest' object to the console.
Console.WriteLine("
The value of 'HaveResponse' property before a response object is obtained :
{0}",myHttpWebRequest.HaveResponse);
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebRequest.HaveResponse)
{
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of Html Page are :
");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Close the Stream object.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse Resource.
myHttpWebResponse.Close();
Console.WriteLine("
Press 'Enter' key to continue..........");
Console.Read();
}
else
{
Console.WriteLine("
The response is not received ");
}
HttpWebRequest.Headers HttpWebRequest.Headers
I n this Article
Specifies a collection of the name/value pairs that make up the HTTP headers.
public override System.Net.WebHeaderCollection Headers { get; set; }
member this.Headers : System.Net.WebHeaderCollection with get, set

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection that contains the name/value pairs that make up the headers for the HTTP request.
Exceptions
InvalidOperationException InvalidOperationException
The request has been started by calling the GetRequestStream(), BeginGetRequestStream(AsyncCallback, Object),
GetResponse(), or BeginGetResponse(AsyncCallback, Object) method.

Examples
The following code example uses the Headers property to print the HTTP header name/value pairs to the console.
// Create a new 'HttpWebRequest' Object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine("
The HttpHeaders are

Name Value
{0}",myHttpWebRequest.Headers);
// Print the HTML contents of the page to the console.
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The HTML contents of page the are :

");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Close the Stream object.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse Resource.
myHttpWebResponse.Close();

Remarks
The Headers collection contains the protocol headers associated with the request. The following table lists the HTTP
headers that are not stored in the Headers collection but are either set by the system or set by properties or methods.
HE AD ER SET BY

Accept Set by the Accept property.

Connection Set by the Connection property and KeepAlive property.

Content-Length Set by the ContentLength property.

Content-Type Set by the ContentType property.

Expect Set by the Expect property.

Date Set by the Date property.

Host Set by the Host property.

If-Modified-Since Set by the IfModifiedSince property.

Range Set by the AddRange method.

Referer Set by the Referer property.

Transfer-Encoding Set by the TransferEncoding property (the SendChunked


property must be true).

User-Agent Set by the UserAgent property.

The Add method throws an ArgumentException if you try to set one of these protected headers.
Changing the Headers property after the request has been started by calling GetRequestStream,
BeginGetRequestStream, GetResponse, or BeginGetResponse method throws an InvalidOperationException.
You should not assume that the header values will remain unchanged, because Web servers and caches may change or
add headers to a Web request.
HttpWebRequest.Host HttpWebRequest.Host
I n this Article
Gets or sets the Host header value to use in an HTTP request independent from the request URI.
public string Host { get; set; }
member this.Host : string with get, set

Returns
String String
The Host header value in the HTTP request.
Exceptions
ArgumentNullException ArgumentNullException
The Host header cannot be set to null .
ArgumentException ArgumentException
The Host header cannot be set to an invalid value.
InvalidOperationException InvalidOperationException
The Host header cannot be set after the HttpWebRequest has already started to be sent.

Remarks
The Host property can be used to set the Host header value to use in an HTTP request independent from the request
URI. The Host property can consist of a hostname and an optional port number. A Host header without port
information implies the default port for the service requested (port 80 for an HTTP URL, for example).
The format for specifying a host and port must follow the rules in section 14.23 of RFC2616 published by the IETF. An
example complying with these requirements that specifies a port of 8080 would be the following value for the Host
property:
www.contoso.com:8080

Using the Host property to explicitly specify a custom Host header value also affects areas caching, cookies, and
authentication. When an application provides credentials for a specific URI prefix, the applications needs to make sure
to use the URI containing the value of the Host header, not the target server in the URI. The key used when caching
resources, uses the Host header value rather than the request URI. Cookies are stored in a CookieContainer and
logically grouped by the server domain name. If the application specifies a Host header, then this value will be used as
domain.
If the Host property is not set, then the Host header value to use in an HTTP request is based on the request URI.
HttpWebRequest HttpWebRequest
I n this Article

Overloads
HttpWebRequest()
Initializes a new instance of the HttpWebRequest class. This
constructor is obsolete.

HttpWebRequest(Uri) HttpWebRequest(Uri)

HttpWebRequest(SerializationInfo, StreamingContext) Http


WebRequest(SerializationInfo, StreamingContext) Initializes a new instance of the HttpWebRequest class from
the specified instances of the SerializationInfo and
StreamingContext classes. This constructor is obsolete.

Remarks
Both HttpWebRequest constructors are obsolete and should not be used. Call the WebRequest.CreateHttp method to
initialize new HttpWebRequest objects.

HttpWebRequest()
Initializes a new instance of the HttpWebRequest class. This constructor is obsolete.
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public HttpWebRequest ();

Attributes ObsoleteAttribute

HttpWebRequest(Uri) HttpWebRequest(Uri)
public HttpWebRequest (Uri uri);
new System.Net.HttpWebRequest : Uri -> System.Net.HttpWebRequest

Parameters
uri Uri Uri

HttpWebRequest(SerializationInfo, StreamingContext)
HttpWebRequest(SerializationInfo, StreamingContext)
Initializes a new instance of the HttpWebRequest class from the specified instances of the SerializationInfo and
StreamingContext classes. This constructor is obsolete.
[System.Obsolete("Serialization is obsoleted for this type", false)]
[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?
linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
protected HttpWebRequest (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.HttpWebRequest : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.HttpWebRequest

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo object that contains the information required to serialize the new HttpWebRequest object.
streamingContext StreamingContext StreamingContext
A StreamingContext object that contains the source and destination of the serialized stream associated with the new
HttpWebRequest object.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Remarks
An application must run in full trust mode when using serialization.
See XML and SOAP Serialization
Also
HttpWebRequest.IfModifiedSince HttpWebRequest.If
ModifiedSince
I n this Article
Gets or sets the value of the If-Modified-Since HTTP header.

public DateTime IfModifiedSince { get; set; }


member this.IfModifiedSince : DateTime with get, set

Returns
DateTime DateTime
A DateTime that contains the contents of the If-Modified-Since HTTP header. The default value is the current date
and time.

Examples
The following code example checks the IfModifiedSince property.
// Create a new 'Uri' object with the mentioned string.
Uri myUri =new Uri("http://www.contoso.com");
// Create a new 'HttpWebRequest' object with the above 'Uri' object.
HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create(myUri);

// Create a new 'DateTime' object.


DateTime targetDate = DateTime.Now;
// Set a target date of a week ago
targetDate.AddDays(-7.0);
myHttpWebRequest.IfModifiedSince = targetDate;

try
{
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine("Response headers for recently modified page
{0}
",myHttpWebResponse.Headers);
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of Html Page are :
");

while (count > 0)


{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Close the Stream object.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse Resource.
myHttpWebResponse.Close();

Console.WriteLine("
Press 'Enter' key to continue.................");
Console.Read();
}
catch(WebException e)
{
if (e.Response != null)
{
if ( ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.NotModified)
Console.WriteLine("
The page has not been modified since "+targetDate);
else
Console.WriteLine("
Unexpected status code = " + ((HttpWebResponse)e.Response).StatusCode);
}
else
Console.WriteLine("
Unexpected Web Exception " + e.Message);
}

Remarks
The IfModifiedSince property is a standard System.DateTime object and can contain a System.DateTimeKind field of
DateTimeKind.Local, DateTimeKind.Utc, or DateTimeKind.Unspecified. Any kind of time can be set when using the
IfModifiedSince property. If DateTimeKind.Unspecified is set or retrieved, the IfModifiedSince property is assumed to
be DateTimeKind.Local (local time).
The classes in the System.Net namespace always write it out the IfModifiedSince property on the wire during
transmission in standard form using GMT (Utc) format.
If the IfModifiedSince property is set to DateTime.MinValue, then the If-Modified-Since HTTP header is removed
from the Headers property and the WebHeaderCollection.
If the IfModifiedSince property is DateTime.MinValue, this indicates that the If-Modified-Since HTTP header is not
included in the Headers property and the WebHeaderCollection.
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.ISerializable.GetObjectData
I n this Article
Populates a SerializationInfo with the data needed to serialize the target object.
[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?
linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.
Attributes ObsoleteAttribute ObsoleteAttribute

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
HttpWebRequest.KeepAlive HttpWebRequest.KeepAlive
I n this Article
Gets or sets a value that indicates whether to make a persistent connection to the Internet resource.
public bool KeepAlive { get; set; }
member this.KeepAlive : bool with get, set

Returns
Boolean Boolean
true if the request to the Internet resource should contain a Connection HTTP header with the value Keep-alive;
otherwise, false . The default is true .

Examples
The following code example sets the KeepAlive property to false to avoid establishing a persistent connection with
the Internet resource.

class HttpWebRequest_Connection
{
static void Main()
{
try
{

// Create a new HttpWebRequest object.Make sure that


// a default proxy is set if you are behind a firewall.
HttpWebRequest myHttpWebRequest1 =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com");

myHttpWebRequest1.KeepAlive=false;
// Assign the response object of HttpWebRequest to a HttpWebResponse variable.
HttpWebResponse myHttpWebResponse1 =
(HttpWebResponse)myHttpWebRequest1.GetResponse();

Console.WriteLine("
The HTTP request Headers for the first request are:
{0}",myHttpWebRequest1.Headers);
Console.WriteLine("Press Enter Key to Continue..........");
Console.Read();

Stream streamResponse=myHttpWebResponse1.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("The contents of the Html page are.......
");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
Console.WriteLine();
// Close the Stream object.
streamResponse.Close();
streamRead.Close();
// Release the resources held by response object.
myHttpWebResponse1.Close();
myHttpWebResponse1.Close();
// Create a new HttpWebRequest object for the specified Uri.
HttpWebRequest myHttpWebRequest2 =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest2.Connection="Close";
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse2 =
(HttpWebResponse)myHttpWebRequest2.GetResponse();
// Release the resources held by response object.
myHttpWebResponse2.Close();
Console.WriteLine("
The Http RequestHeaders are
{0}",myHttpWebRequest2.Headers);
Console.WriteLine("
Press 'Enter' Key to Continue.........");
Console.Read();
}
catch(ArgumentException e)
{
Console.WriteLine("
The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to
'Close'");
Console.WriteLine("
{0}",e.Message);
}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source :{0} " , e.Source);
Console.WriteLine("Message :{0} " , e.Message);
}
}
}

Remarks
Set this property to true to send a Connection HTTP header with the value Keep-alive. An application uses KeepAlive
to indicate a preference for persistent connections. When the KeepAlive property is true , the application makes
persistent connections to the servers that support them.
Note

When using HTTP/1.1, Keep-Alive is on by default. Setting KeepAlive to false may result in sending a
Connection: Close header to the server.
HttpWebRequest.MaximumAutomaticRedirections Http
WebRequest.MaximumAutomaticRedirections
I n this Article
Gets or sets the maximum number of redirects that the request follows.

public int MaximumAutomaticRedirections { get; set; }


member this.MaximumAutomaticRedirections : int with get, set

Returns
Int32 Int32
The maximum number of redirection responses that the request follows. The default value is 50.
Exceptions
ArgumentException ArgumentException
The value is set to 0 or less.

Examples
The following code example sets the value of this property.
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test


{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

// Set some reasonable limits on resources used by this request


request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Console.WriteLine ("Content length is {0}", response.ContentLength);


Console.WriteLine ("Content type is {0}", response.ContentType);

// Get the stream associated with the response.


Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");


Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542


Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Remarks
The MaximumAutomaticRedirections property sets the maximum number of redirections for the request to follow if
the AllowAutoRedirect property is true .
HttpWebRequest.MaximumResponseHeadersLength Http
WebRequest.MaximumResponseHeadersLength
I n this Article
Gets or sets the maximum allowed length of the response headers.

public int MaximumResponseHeadersLength { get; set; }


member this.MaximumResponseHeadersLength : int with get, set

Returns
Int32 Int32
The length, in kilobytes (1024 bytes), of the response headers.
Exceptions
InvalidOperationException InvalidOperationException
The property is set after the request has already been submitted.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value is less than 0 and is not equal to -1.

Examples
The following code example sets the value of this property.
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test


{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

// Set some reasonable limits on resources used by this request


request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Console.WriteLine ("Content length is {0}", response.ContentLength);


Console.WriteLine ("Content type is {0}", response.ContentType);

// Get the stream associated with the response.


Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");


Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542


Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Remarks
The length of the response header includes the response status line and any extra control characters that are received
as part of HTTP protocol. A value of -1 means no limit is imposed on the response headers; a value of 0 means that all
requests fail.
If the MaximumResponseHeadersLength property is not explicitly set, it defaults to the value of the
DefaultMaximumResponseHeadersLength property.
If the length of the response header received exceeds the value of the MaximumResponseHeadersLength property, the
EndGetResponse or GetResponse methods will throw a WebException with the Status property set to
MessageLengthLimitExceeded.
HttpWebRequest.MediaType HttpWebRequest.Media
Type
I n this Article
Gets or sets the media type of the request.

public string MediaType { get; set; }


member this.MediaType : string with get, set

Returns
String String
The media type of the request. The default value is null .

Remarks
The value of the MediaType property affects the CharacterSet property. When you set the MediaType in the request,
the corresponding media type is chosen from the list of character sets returned in the response Content-type HTTP
header.
HttpWebRequest.Method HttpWebRequest.Method
I n this Article
Gets or sets the method for the request.
public override string Method { get; set; }
member this.Method : string with get, set

Returns
String String
The request method to use to contact the Internet resource. The default value is GET.
Exceptions
ArgumentException ArgumentException
No method is supplied.
-or-
The method string contains invalid characters.

Examples
The following code example sets the Method property to POST.
// Set the 'Method' property of the 'Webrequest' to 'POST'.
myHttpWebRequest.Method = "POST";
Console.WriteLine ("
Please enter the data to be posted to the (http://www.contoso.com/codesnippets/next.asp) Uri :");

// Create a new string object to POST data to the Url.


string inputData = Console.ReadLine ();

string postData = "firstone=" + inputData;


ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.


myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.


myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);


Console.WriteLine ("The value of 'ContentLength' property after sending the data is {0}",
myHttpWebRequest.ContentLength);

// Close the Stream object.


newStream.Close ();

Remarks
The Method property can be set to any of the HTTP 1.1 protocol verbs: GET, HEAD, POST, PUT, DELETE, TRACE, or
OPTIONS.
If the ContentLength property is set to any value other than -1, the Method property must be set to a protocol
property that uploads data.
HttpWebRequest.Pipelined HttpWebRequest.Pipelined
I n this Article
Gets or sets a value that indicates whether to pipeline the request to the Internet resource.
public bool Pipelined { get; set; }
member this.Pipelined : bool with get, set

Returns
Boolean Boolean
true if the request should be pipelined; otherwise, false . The default is true .

Examples
The following code example prints the value of the Pipelined property to the console.
// Create a 'HttpWebRequest' object.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(myUri);
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
// Display the contents of the page to the console.
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuffer = new Char[256];
int count = streamRead.Read( readBuffer, 0, 256 );
Console.WriteLine("
The contents of HTML page are.......");
while (count > 0)
{
String outputData = new String(readBuffer, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuffer, 0, 256);
}
Console.WriteLine("
HTTP Request Headers :

{0}",myHttpWebRequest.Headers);
Console.WriteLine("
HTTP Response Headers :

{0}",myHttpWebResponse.Headers);
streamRead.Close();
streamResponse.Close();
// Release the response object resources.
myHttpWebResponse.Close();
Console.WriteLine("
'Pipelined' property is:{0}",myHttpWebRequest.Pipelined);
Console.WriteLine("
Press 'Enter' Key to Continue......");
Console.Read();

Remarks
An application uses the Pipelined property to indicate a preference for pipelined connections. When Pipelined is true ,
an application makes pipelined connections to the servers that support them.
Pipelined connections are made only when the KeepAlive property is also true .
HttpWebRequest.PreAuthenticate HttpWebRequest.Pre
Authenticate
I n this Article
Gets or sets a value that indicates whether to send an Authorization header with the request.

public override bool PreAuthenticate { get; set; }


member this.PreAuthenticate : bool with get, set

Returns
Boolean Boolean
true to send an HTTP Authorization header with requests after authentication has taken place; otherwise, false . The
default is false .

Remarks
After a client request to a specific Uri is successfully authenticated, if PreAuthenticate is true and credentials are
supplied, the Authorization header is sent with each request to any Uri that matches the specific Uri up to the last
forward slash. So if the client request successfully authenticated to a specific Uri that contains the following:
http://www.contoso.com/firstpath/

Then the Authorization header for preauthentication is sent with each request to any of the following Uri instances:
http://www.contoso.com/firstpath/

http://www.contoso.com/firstpath/default

http://www.contoso.com/firstpath/default.html

http://www.contoso.com/firstpath/sample.html

However, the Authorization header is not sent with requests to any of the following Uri instances:
http://www.contoso.com/

http://www.contoso.com/firstpath

http://www.contoso.com/secondpath/

If the client request to a specific Uri is not successfully authenticated, the request uses standard authentication
procedures.
With the exception of the first request, the PreAuthenticate property indicates whether to send authentication
information with subsequent requests to a Uri that matches the specific Uri up to the last forward slash without waiting
to be challenged by the server.
The following dialog between client and server illustrates the effect of this property. The dialog assumes that basic
authentication is in use.
PreAuthenticate is false :
Client: GET someUrl
Server: 401 WWW -Authenticate Basic
Client: GET with Authorization headers
Server: 200 OK
Client: GET someUrl
Server: 401 WWW -Authenticate Basic
Client: GET with Authorization headers
Server: 200 OK
PreAuthenticate is true :
Client: GET someUrl
Server: 401 WWW -Authenticate Basic
Client: GET with Authorization headers
Server: 200 OK
Client: GET someUrl with Authorization headers
If the authentication scheme does not support preauthentication, the value of this property is ignored.
HttpWebRequest.ProtocolVersion HttpWebRequest.
ProtocolVersion
I n this Article
Gets or sets the version of HTTP to use for the request.

public Version ProtocolVersion { get; set; }


member this.ProtocolVersion : Version with get, set

Returns
Version Version
The HTTP version to use for the request. The default is Version11.
Exceptions
ArgumentException ArgumentException
The HTTP version is set to a value other than 1.0 or 1.1.

Examples
The following code example sets the ProtocolVersion Property.
// Create a new 'HttpWebRequest' Object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");
// Use the existing 'ProtocolVersion' , and display it onto the console.
Console.WriteLine("
The 'ProtocolVersion' of the protocol used is {0}",myHttpWebRequest.ProtocolVersion);
// Set the 'ProtocolVersion' property of the 'HttpWebRequest' to 'Version1.0' .
myHttpWebRequest.ProtocolVersion=HttpVersion.Version10;
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine("
The 'ProtocolVersion' of the protocol changed to {0}",myHttpWebRequest.ProtocolVersion);
Console.WriteLine("
The protocol version of the response object is {0}",myHttpWebResponse.ProtocolVersion);

Remarks
The HttpWebRequest class supports only versions 1.0 and 1.1 of HTTP. Setting ProtocolVersion to a different version
throws an exception.
Note

To set the HTTP version of the current request, use the Version10 and Version11 fields of the HttpVersion class.
HttpWebRequest.Proxy HttpWebRequest.Proxy
I n this Article
Gets or sets proxy information for the request.
public override System.Net.IWebProxy Proxy { get; set; }
member this.Proxy : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
The IWebProxy object to use to proxy the request. The default value is set by calling the Select property.
Exceptions
ArgumentNullException ArgumentNullException
Proxy is set to null .
InvalidOperationException InvalidOperationException
The request has been started by calling GetRequestStream(), BeginGetRequestStream(AsyncCallback, Object),
GetResponse(), or BeginGetResponse(AsyncCallback, Object).
SecurityException SecurityException
The caller does not have permission for the requested operation.

Examples
The following code example uses the Proxy method to get the proxy information for the request.
// Create a new request to the mentioned URL.
HttpWebRequest myWebRequest=(HttpWebRequest)WebRequest.Create("http://www.microsoft.com");

// Obtain the 'Proxy' of the Default browser.


IWebProxy proxy = myWebRequest.Proxy;
// Print the Proxy Url to the console.
if (proxy != null)
{
Console.WriteLine("Proxy: {0}", proxy.GetProxy(myWebRequest.RequestUri));
}
else
{
Console.WriteLine("Proxy is null; no proxy will be used");
}

WebProxy myProxy=new WebProxy();

Console.WriteLine("
Please enter the new Proxy Address that is to be set:");
Console.WriteLine("(Example:http://myproxy.example.com:port)");
string proxyAddress;

try
{
proxyAddress =Console.ReadLine();
if(proxyAddress.Length>0)
{
Console.WriteLine("
Please enter the Credentials (may not be needed)");
Console.WriteLine("Username:");
string username;
username =Console.ReadLine();
Console.WriteLine("
Password:");
string password;
password =Console.ReadLine();
// Create a new Uri object.
Uri newUri=new Uri(proxyAddress);
// Associate the newUri object to 'myProxy' object so that new myProxy settings can be set.
myProxy.Address=newUri;
// Create a NetworkCredential object and associate it with the
// Proxy property of request object.
myProxy.Credentials=new NetworkCredential(username,password);
myWebRequest.Proxy=myProxy;
}
Console.WriteLine("
The Address of the new Proxy settings are {0}",myProxy.Address);
HttpWebResponse myWebResponse=(HttpWebResponse)myWebRequest.GetResponse();

Remarks
The Proxy property identifies the WebProxy object to use to process requests to Internet resources. To specify that no
proxy should be used, set the Proxy property to the proxy instance returned by the
GlobalProxySelection.GetEmptyWebProxy method.
The local computer or application config file may specify that a default proxy be used. If the Proxy property is specified,
then the proxy settings from the Proxy property override the local computer or application config file and the
HttpWebRequest instance will use the proxy settings specified. If no proxy is specified in a config file and the Proxy
property is unspecified, the HttpWebRequest class uses the proxy settings inherited from Internet Explorer on the local
computer. If there are no proxy settings in Internet Explorer, the request is sent directly to the server.
The HttpWebRequest class parses a proxy bypass list with wildcard characters inherited from Internet Explorer the
same as the bypass list is parsed directly by Internet Explorer. For example, the HttpWebRequest class will parse a
bypass list of "nt*" from Internet Explorer as a regular expression of "nt.*". So a URL of " http://nt.com " would bypass
the proxy using the HttpWebRequest class and using Internet Explorer.
The HttpWebRequest class supports local proxy bypass. The class considers a destination to be local if any of the
following conditions are met:
The destination contains a flat name (no dots in the URL ).
The destination contains a loopback address (Loopback or IPv6Loopback) or the destination contains an IPAddress
assigned to the local computer.
The domain suffix of the destination matches the local computer's domain suffix (DomainName).
Changing the Proxy property after the request has been started by calling the GetRequestStream,
BeginGetRequestStream, GetResponse, or BeginGetResponse method throws an InvalidOperationException. For
information on the proxy element see &lt;defaultProxy&gt; Element (Network Settings).
See DefaultProxy Element (Network Settings)
Also Configuring Internet Applications
Proxy Configuration
Automatic Proxy Detection
HttpWebRequest.ReadWriteTimeout HttpWebRequest.
ReadWriteTimeout
I n this Article
Gets or sets a time-out in milliseconds when writing to or reading from a stream.

public int ReadWriteTimeout { get; set; }


member this.ReadWriteTimeout : int with get, set

Returns
Int32 Int32
The number of milliseconds before the writing or reading times out. The default value is 300,000 milliseconds (5
minutes).
Exceptions
InvalidOperationException InvalidOperationException
The request has already been sent.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for a set operation is less than or equal to zero and is not equal to Infinite

Examples
The following code example shows how to set the ReadWriteTimeout property.

HttpWebRequest myReq =
(HttpWebRequest)WebRequest.Create("http://www.contoso.com/");

myReq.ReadWriteTimeout = 100000;

Remarks
The ReadWriteTimeout property is used when writing to the stream returned by the GetRequestStream method or
reading from the stream returned by the GetResponseStream method.
Specifically, the ReadWriteTimeout property controls the time-out for the Read method, which is used to read the
stream returned by the GetResponseStream method, and for the Write method, which is used to write to the stream
returned by the GetRequestStream method.
To specify the amount of time to wait for the request to complete, use the Timeout property.
See TimeoutTimeout
Also
HttpWebRequest.Referer HttpWebRequest.Referer
I n this Article
Gets or sets the value of the Referer HTTP header.

public string Referer { get; set; }


member this.Referer : string with get, set

Returns
String String
The value of the Referer HTTP header. The default value is null .

Examples
The following code example sets the Referer property.
// Create a 'HttpWebRequest' object.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(myUri);
// Set referer property to http://www.microsoft.com .
myHttpWebRequest.Referer="http://www.microsoft.com";
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
// Display the contents of the page to the console.
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuffer = new Char[256];
int count = streamRead.Read( readBuffer, 0, 256 );
Console.WriteLine("
The contents of HTML page are.......");
while (count > 0)
{
String outputData = new String(readBuffer, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuffer, 0, 256);
}
Console.WriteLine("
HTTP Request Headers :

{0}",myHttpWebRequest.Headers);
Console.WriteLine("
HTTP Response Headers :

{0}",myHttpWebResponse.Headers);
streamRead.Close();
streamResponse.Close();
// Release the response object resources.
myHttpWebResponse.Close();
Console.WriteLine("Referer to the site is:{0}",myHttpWebRequest.Referer);

Remarks
If the AllowAutoRedirect property is true , the Referer property is set automatically when the request is redirected to
another site.
To clear the Referer HTTP header, set the Referer property to null .
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.RequestUri HttpWebRequest.Request
Uri
I n this Article
Gets the original Uniform Resource Identifier (URI) of the request.

public override Uri RequestUri { get; }


member this.RequestUri : Uri

Returns
Uri Uri
A Uri that contains the URI of the Internet resource passed to the Create(String) method.

Examples
The following code example checks to see if the HttpWebRequest object req was redirected to another location to
fulfill the request, and sets the value of the hasChanged variable to true if the request was redirected; otherwise,
hasChanged is set to false .

bool hasChanged = (req.RequestUri != req.Address);

Remarks
The Uri object passed to HttpWebRequest by the call to WebRequest.Create.
Following a redirection header does not change the RequestUri property. To get the actual URI that responded to the
request, examine the Address property.
HttpWebRequest.SendChunked HttpWebRequest.Send
Chunked
I n this Article
Gets or sets a value that indicates whether to send data in segments to the Internet resource.

public bool SendChunked { get; set; }


member this.SendChunked : bool with get, set

Returns
Boolean Boolean
true to send data to the Internet resource in segments; otherwise, false . The default value is false .

Exceptions
InvalidOperationException InvalidOperationException
The request has been started by calling the GetRequestStream(), BeginGetRequestStream(AsyncCallback, Object),
GetResponse(), or BeginGetResponse(AsyncCallback, Object) method.

Examples
The following code example sets the SendChunked property to true so that data can be sent in segments to the
Internet resource.
// A new 'HttpWebRequest' object is created.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
myHttpWebRequest.SendChunked = true;
// 'TransferEncoding' property is set to 'gzip'.
myHttpWebRequest.TransferEncoding = "gzip";
Console.WriteLine("
Please Enter the data to be posted to the (http://<machine name>/CodeSnippetTest.asp) uri:");

string inputData = Console.ReadLine();


string postData = "testdata=" + inputData;
// 'Method' property of 'HttpWebRequest' class is set to POST.
myHttpWebRequest.Method = "POST";
ASCIIEncoding encodedData = new ASCIIEncoding();
byte[] byteArray = encodedData.GetBytes(postData);
// 'ContentType' property of the 'HttpWebRequest' class is set to "application/x-www-form-
urlencoded".
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
// 'ContentLength' property is set to Length of the data to be posted.
myHttpWebRequest.ContentLength = byteArray.Length;
Stream newStream = myHttpWebRequest.GetRequestStream();
newStream.Write(byteArray, 0, byteArray.Length);
newStream.Close();
Console.WriteLine("
Data has been posted to the Uri

Please wait for the response..........");

// The response object of 'HttpWebRequest' is assigned to a 'HttpWebResponse' variable.


HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Displaying the contents of the page to the console
Stream streamResponse = myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
Char[] readBuff = new Char[256];
int count = streamRead.Read(readBuff, 0, 256);
Console.WriteLine("
The contents of the HTML page are : ");

while (count > 0)


{
String outputData = new String(readBuff, 0, count);
Console.WriteLine(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Release the response object resources.
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();

Remarks
When SendChunked is true , the request sends data to the Internet resource in segments. The Internet resource must
support receiving chunked data.
Changing the SendChunked property after the request has been started by calling the GetRequestStream,
BeginGetRequestStream, GetResponse, or BeginGetResponse method throws an InvalidOperationException.
HttpWebRequest.ServerCertificateValidationCallback
HttpWebRequest.ServerCertificateValidationCallback
I n this Article
Gets or sets a callback function to validate the server certificate.

public System.Net.Security.RemoteCertificateValidationCallback ServerCertificateValidationCallback {


get; set; }
member this.ServerCertificateValidationCallback :
System.Net.Security.RemoteCertificateValidationCallback with get, set

Returns
RemoteCertificateValidationCallback RemoteCertificateValidationCallback
A callback function to validate the server certificate.

Remarks
The default is that no callback function is set and the ServerCertificateValidationCallback property is null .
HttpWebRequest.ServicePoint HttpWebRequest.Service
Point
I n this Article
Gets the service point to use for the request.

public System.Net.ServicePoint ServicePoint { get; }


member this.ServicePoint : System.Net.ServicePoint

Returns
ServicePoint ServicePoint
A ServicePoint that represents the network connection to the Internet resource.

Examples
private static void makeWebRequest(int hashCode, string Uri)
{
HttpWebResponse res = null;

// Make sure that the idle time has elapsed, so that a new
// ServicePoint instance is created.
Console.WriteLine("Sleeping for 2 sec.");
Thread.Sleep(2000);
try
{
// Create a request to the passed URI.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(Uri);

Console.WriteLine("
Connecting to " + Uri + " ............");

// Get the response object.


res = (HttpWebResponse)req.GetResponse();
Console.WriteLine("Connected.
");

ServicePoint currentServicePoint = req.ServicePoint;

// Display new service point properties.


int currentHashCode = currentServicePoint.GetHashCode();

Console.WriteLine("New service point hashcode: " + currentHashCode);


Console.WriteLine("New service point max idle time: " + currentServicePoint.MaxIdleTime);
Console.WriteLine("New service point is idle since " + currentServicePoint.IdleSince );

// Check that a new ServicePoint instance has been created.


if (hashCode == currentHashCode)
Console.WriteLine("Service point reused.");
else
Console.WriteLine("A new service point created.") ;
}
catch (Exception e)
{
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
finally
{
if (res != null)
res.Close();
}
}

Remarks
The ServicePoint.Address property may be different from HttpWebRequest.Address if the request is redirected.
HttpWebRequest.SupportsCookieContainer HttpWeb
Request.SupportsCookieContainer
I n this Article
Gets a value that indicates whether the request provides support for a CookieContainer.

public virtual bool SupportsCookieContainer { get; }


member this.SupportsCookieContainer : bool

Returns
Boolean Boolean
true if the request provides support for a CookieContainer; otherwise, false .
HttpWebRequest.Timeout HttpWebRequest.Timeout
I n this Article
Gets or sets the time-out value in milliseconds for the GetResponse() and GetRequestStream() methods.
public override int Timeout { get; set; }
member this.Timeout : int with get, set

Returns
Int32 Int32
The number of milliseconds to wait before the request times out. The default value is 100,000 milliseconds (100
seconds).
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified is less than zero and is not Infinite.

Examples
The following code example sets the Timeout property of the HttpWebRequest object.
// Create a new 'HttpWebRequest' Object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
Console.WriteLine("
The timeout time of the request before setting the property is {0}
milliSeconds.",myHttpWebRequest.Timeout);
// Set the 'Timeout' property of the HttpWebRequest to 10 milliseconds.
myHttpWebRequest.Timeout=10;
// Display the 'Timeout' property of the 'HttpWebRequest' on the console.
Console.WriteLine("
The timeout time of the request after setting the timeout is {0}
milliSeconds.",myHttpWebRequest.Timeout);
// A HttpWebResponse object is created and is GetResponse Property of the HttpWebRequest associated
with it
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();

Remarks
Timeout is the number of milliseconds that a subsequent synchronous request made with the GetResponse method
waits for a response, and the GetRequestStream method waits for a stream. The Timeout applies to the entire request
and response, not individually to the GetRequestStream and GetResponse method calls. If the resource is not returned
within the time-out period, the request throws a WebException with the Status property set to
WebExceptionStatus.Timeout.
The Timeout property must be set before the GetRequestStream or GetResponse method is called. Changing the
Timeout property after calling the GetRequestStream or GetResponse method has no effect
The Timeout property has no effect on asynchronous requests made with the BeginGetResponse or
BeginGetRequestStream method.
Cautio n

In the case of asynchronous requests, the client application implements its own time-out mechanism. Refer to the
example in the BeginGetResponse method.
To specify the amount of time to wait before a read or write operation times out, use the ReadWriteTimeout property.
A Domain Name System (DNS ) query may take up to 15 seconds to return or time out. If your request contains a host
name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more
before a WebException is thrown to indicate a timeout on your request.
See ReadWriteTimeoutReadWriteTimeout
Also
HttpWebRequest.TransferEncoding HttpWebRequest.
TransferEncoding
I n this Article
Gets or sets the value of the Transfer-encoding HTTP header.

public string TransferEncoding { get; set; }


member this.TransferEncoding : string with get, set

Returns
String String
The value of the Transfer-encoding HTTP header. The default value is null .

Exceptions
InvalidOperationException InvalidOperationException
TransferEncoding is set when SendChunked is false .
ArgumentException ArgumentException
TransferEncoding is set to the value "Chunked".

Remarks
Before you can set the TransferEncoding property, you must first set the SendChunked property to true . Clearing
TransferEncoding by setting it to null has no effect on the value of SendChunked.
Values assigned to the TransferEncoding property replace any existing contents.
Note

The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.
HttpWebRequest.UnsafeAuthenticatedConnection
Sharing HttpWebRequest.UnsafeAuthenticated
ConnectionSharing
I n this Article
Gets or sets a value that indicates whether to allow high-speed NTLM -authenticated connection sharing.
public bool UnsafeAuthenticatedConnectionSharing { get; set; }
member this.UnsafeAuthenticatedConnectionSharing : bool with get, set

Returns
Boolean Boolean
true to keep the authenticated connection open; otherwise, false .

Remarks
The default value for this property is false , which causes the current connection to be closed after a request is
completed. Your application must go through the authentication sequence every time it issues a new request.
If this property is set to true , the connection used to retrieve the response remains open after the authentication has
been performed. In this case, other requests that have this property set to true may use the connection without re-
authenticating. In other words, if a connection has been authenticated for user A, user B may reuse A's connection; user
B's request is fulfilled based on the credentials of user A.
Cautio n

Because it is possible for an application to use the connection without being authenticated, you need to be sure that
there is no administrative vulnerability in your system when setting this property to true . If your application sends
requests for multiple users (impersonates multiple user accounts) and relies on authentication to protect resources, do
not set this property to true unless you use connection groups as described below.
You may want to consider enabling this mechanism if your are having performance problems and your application is
running on a Web server with integrated Windows authentication.
Enabling this setting opens the system to security risks. If you set the UnsafeAuthenticatedConnectionSharing
property to true be sure to take the following precautions:
Use the ConnectionGroupName property to manage connections for different users. This avoids the potential use of
the connection by non-authenticated applications. For example, user A should have a unique connection group name
that is different from user B. This provides a layer of isolation for each user account.
Run your application in a protected environment to help avoid possible connection exploits.
If you control the back-end server, as an alternative you might consider turning off authentication persistence. This
increases performance to a lesser degree, but it is safer. For more details, search for AuthPersistence in the MSDN
library at http://msdn.microsoft.com/library.
Note

If both PreAuthenticate and UnsafeAuthenticatedConnectionSharing are set to true , each request is sent using a
connection from the unsafe pool, but with an Authorization header.
HttpWebRequest.UseDefaultCredentials HttpWeb
Request.UseDefaultCredentials
I n this Article
Gets or sets a Boolean value that controls whether default credentials are sent with requests.

public override bool UseDefaultCredentials { get; set; }


member this.UseDefaultCredentials : bool with get, set

Returns
Boolean Boolean
true if the default credentials are used; otherwise, false . The default value is false .

Exceptions
InvalidOperationException InvalidOperationException
You attempted to set this property after the request was sent.

Remarks
Set this property to true when requests made by this HttpWebRequest object should, if requested by the server, be
authenticated using the credentials of the currently logged on user. For client applications, this is the desired behavior
in most scenarios. For middle-tier applications, such as ASP.NET applications, instead of using this property, you would
typically set the Credentials property to the credentials of the client on whose behalf the request is made.
HttpWebRequest.UserAgent HttpWebRequest.UserAgent
I n this Article
Gets or sets the value of the User-agent HTTP header.

public string UserAgent { get; set; }


member this.UserAgent : string with get, set

Returns
String String
The value of the User-agent HTTP header. The default value is null .
The value for this property is stored in WebHeaderCollection. If WebHeaderCollection is set, the property value is lost.

Examples
The following code example sets the UserAgent property.
// Create a new 'HttpWebRequest' object to the mentioned URL.
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create("http://www.contoso.com");
myHttpWebRequest.UserAgent=".NET Framework Test Client";
// Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
// Display the contents of the page to the console.
Stream streamResponse=myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of HTML Page are :
");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}
// Release the response object resources.
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();
HttpWebResponse HttpWebResponse Class
Provides an HTTP -specific implementation of the WebResponse class.

D eclaration
[System.Serializable]
public class HttpWebResponse : System.Net.WebResponse, IDisposable,
System.Runtime.Serialization.ISerializable
type HttpWebResponse = class
inherit WebResponse
interface ISerializable
interface IDisposable

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
WebResponse WebResponse

Remarks
This class contains support for HTTP -specific uses of the properties and methods of the WebResponse class. The
HttpWebResponse class is used to build HTTP stand-alone client applications that send HTTP requests and receive
HTTP responses.
Note

Do not confuse HttpWebResponse with the HttpResponse class that is used in ASP.NET applications and whose
methods and properties are exposed through ASP.NET's intrinsic Response object.
You should never directly create an instance of the HttpWebResponse class. Instead, use the instance returned by a call
to HttpWebRequest.GetResponse. You must call either the Stream.Close or the HttpWebResponse.Close method to
close the response and release the connection for reuse. It is not necessary to call both Stream.Close and
HttpWebResponse.Close, but doing so does not cause an error.
Common header information returned from the Internet resource is exposed as properties of the class. See the
following table for a complete list. Other headers can be read from the Headers property as name/value pairs.
The following table shows the common HTTP headers that are available through properties of the HttpWebResponse
class.

HE AD ER PR O PER T Y

Content-Encoding ContentEncoding

Content-Length ContentLength

Content-Type ContentType

Last-Modified LastModified

Server Server

The contents of the response from the Internet resource are returned as a Stream by calling the GetResponseStream
method.

Constructors
HttpWebResponse()
HttpWebResponse()

Initializes a new instance of the HttpWebResponse class.

HttpWebResponse(SerializationInfo, StreamingContext)
HttpWebResponse(SerializationInfo, StreamingContext)

Initializes a new instance of the HttpWebResponse class from the specified SerializationInfo and
StreamingContext instances.

Properties
CharacterSet
CharacterSet

Gets the character set of the response.

ContentEncoding
ContentEncoding

Gets the method that is used to encode the body of the response.

ContentLength
ContentLength

Gets the length of the content returned by the request.

ContentType
ContentType

Gets the content type of the response.

Cookies
Cookies

Gets or sets the cookies that are associated with this response.

Headers
Headers

Gets the headers that are associated with this response from the server.
IsMutuallyAuthenticated
IsMutuallyAuthenticated

Gets a Boolean value that indicates whether both client and server were authenticated.

LastModified
LastModified

Gets the last date and time that the contents of the response were modified.

Method
Method

Gets the method that is used to return the response.

ProtocolVersion
ProtocolVersion

Gets the version of the HTTP protocol that is used in the response.

ResponseUri
ResponseUri

Gets the URI of the Internet resource that responded to the request.

Server
Server

Gets the name of the server that sent the response.

StatusCode
StatusCode

Gets the status of the response.

StatusDescription
StatusDescription

Gets the status description returned with the response.

SupportsHeaders
SupportsHeaders

Gets a value that indicates whether headers are supported.


Methods
Close()
Close()

Closes the response stream.

Dispose(Boolean)
Dispose(Boolean)

Releases the unmanaged resources used by the HttpWebResponse, and optionally disposes of the managed
resources.

GetHashCode()
GetHashCode()

Returns a hash value for a HttpWebResponse instance.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

GetResponseHeader(String)
GetResponseHeader(String)

Gets the contents of a header that was returned with the response.

GetResponseStream()
GetResponseStream()

Gets the stream that is used to read the body of the response from the server.

IDisposable.Dispose()
IDisposable.Dispose()

Releases all resources used by the HttpWebResponse.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Serializes this instance into the specified SerializationInfo object.

See Also
WebResponse WebResponse
HttpWebResponse.CharacterSet HttpWebResponse.
CharacterSet
I n this Article
Gets the character set of the response.

public string CharacterSet { get; }


member this.CharacterSet : string

Returns
String String
A string that contains the character set of the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example obtains the character set of the response.
try
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

Console.WriteLine("The encoding method used is: " + myHttpWebResponse.ContentEncoding);


Console.WriteLine("The character set used is :" + myHttpWebResponse.CharacterSet);

char seperator = '/';


String contenttype = myHttpWebResponse.ContentType;
// Retrieve 'text' if the content type is of 'text/html.
String maintype = contenttype.Substring(0,contenttype.IndexOf(seperator));
// Display only 'text' type.
if (String.Compare(maintype,"text") == 0)
{
Console.WriteLine("
Content type is 'text'.");

Remarks
The CharacterSet property contains a value that describes the character set of the response. This character set
information is taken from the header returned with the response.
HttpWebResponse.Close HttpWebResponse.Close
I n this Article
Closes the response stream.
public override void Close ();
override this.Close : unit -> unit

Exceptions
ObjectDisposedException ObjectDisposedException
.NET Core only: This HttpWebResponse object has been disposed.

Examples
The following example demonstrates how to close a HttpWebResponse.
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for a response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine("
Response Received.Trying to Close the response stream..");
// Releases the resources of the response.
myHttpWebResponse.Close();
Console.WriteLine("
Response Stream successfully closed");

Remarks
The Close method closes the response stream and releases the connection to the resource for reuse by other requests.
You should not access any properties of the HttpWebResponse object after the call to the Close method. On .NET
Core, an ObjectDisposedException is thrown.
You must call either the Stream.Close or the HttpWebResponse.Close method to close the stream and release the
connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not
cause an error. Failure to close the stream can cause your application to run out of connections.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
HttpWebResponse.ContentEncoding HttpWebResponse.
ContentEncoding
I n this Article
Gets the method that is used to encode the body of the response.

public string ContentEncoding { get; }


member this.ContentEncoding : string

Returns
String String
A string that describes the method that is used to encode the body of the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example uses the ContentEncoding property to obtain the value of the Content-Encoding header
returned with the response.
try
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

Console.WriteLine("The encoding method used is: " + myHttpWebResponse.ContentEncoding);


Console.WriteLine("The character set used is :" + myHttpWebResponse.CharacterSet);

char seperator = '/';


String contenttype = myHttpWebResponse.ContentType;
// Retrieve 'text' if the content type is of 'text/html.
String maintype = contenttype.Substring(0,contenttype.IndexOf(seperator));
// Display only 'text' type.
if (String.Compare(maintype,"text") == 0)
{
Console.WriteLine("
Content type is 'text'.");

Remarks
The ContentEncoding property contains the value of the Content-Encoding header returned with the response.
HttpWebResponse.ContentLength HttpWebResponse.
ContentLength
I n this Article
Gets the length of the content returned by the request.

public override long ContentLength { get; }


member this.ContentLength : int64

Returns
Int64 Int64
The number of bytes returned by the request. Content length does not include header information.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example displays the value of this property.
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test


{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

// Set some reasonable limits on resources used by this request


request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Console.WriteLine ("Content length is {0}", response.ContentLength);


Console.WriteLine ("Content type is {0}", response.ContentType);

// Get the stream associated with the response.


Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");


Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542


Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Remarks
The ContentLength property contains the value of the Content-Length header returned with the response. If the
Content-Length header is not set in the response, ContentLength is set to the value -1.
HttpWebResponse.ContentType HttpWebResponse.
ContentType
I n this Article
Gets the content type of the response.

public override string ContentType { get; }


member this.ContentType : string

Returns
String String
A string that contains the content type of the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example displays the value of this property.
using System;
using System.Net;
using System.Text;
using System.IO;

public class Test


{
// Specify the URL to receive the request.
public static void Main (string[] args)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create (args[0]);

// Set some reasonable limits on resources used by this request


request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
// Set credentials to use for this request.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Console.WriteLine ("Content length is {0}", response.ContentLength);


Console.WriteLine ("Content type is {0}", response.ContentType);

// Get the stream associated with the response.


Stream receiveStream = response.GetResponseStream ();

// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

Console.WriteLine ("Response stream received.");


Console.WriteLine (readStream.ReadToEnd ());
response.Close ();
readStream.Close ();
}
}

/*
The output from this example will vary depending on the value passed into Main
but will be similar to the following:

Content length is 1542


Content type is text/html; charset=utf-8
Response stream received.
<html>
...
</html>

*/

Remarks
The ContentType property contains the value of the Content-Type header returned with the response.
HttpWebResponse.Cookies HttpWebResponse.Cookies
I n this Article
Gets or sets the cookies that are associated with this response.
public virtual System.Net.CookieCollection Cookies { get; set; }
member this.Cookies : System.Net.CookieCollection with get, set

Returns
CookieCollection CookieCollection
A CookieCollection that contains the cookies that are associated with this response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example sends a request to a URL and displays the cookies returned in the response.
using System.Net;
using System;
namespace Examples.System.Net.Cookies
{
// This example is run at the command line.
// Specify one argument: the name of the host to
// send the request to.
// If the request is sucessful, the example displays the contents of the cookies
// returned by the host.

public class CookieExample


{
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Specify the URL to receive the request.");
Environment.Exit(1);
}
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

// Print the properties of each cookie.


foreach (Cookie cook in response.Cookies)
{
Console.WriteLine("Cookie:");
Console.WriteLine("{0} = {1}", cook.Name, cook.Value);
Console.WriteLine("Domain: {0}", cook.Domain);
Console.WriteLine("Path: {0}", cook.Path);
Console.WriteLine("Port: {0}", cook.Port);
Console.WriteLine("Secure: {0}", cook.Secure);

Console.WriteLine("When issued: {0}", cook.TimeStamp);


Console.WriteLine("Expires: {0} (expired? {1})",
cook.Expires, cook.Expired);
cook.Expires, cook.Expired);
Console.WriteLine("Don't save: {0}", cook.Discard);
Console.WriteLine("Comment: {0}", cook.Comment);
Console.WriteLine("Uri for comments: {0}", cook.CommentUri);
Console.WriteLine("Version: RFC {0}" , cook.Version == 1 ? "2109" : "2965");

// Show the string representation of the cookie.


Console.WriteLine ("String: {0}", cook.ToString());
}
}
}
}

// Output from this example will be vary depending on the host name specified,
// but will be similar to the following.
/*
Cookie:
CustomerID = 13xyz
Domain: .contoso.com
Path: /
Port:
Secure: False
When issued: 1/14/2003 3:20:57 PM
Expires: 1/17/2013 11:14:07 AM (expired? False)
Don't save: False
Comment:
Uri for comments:
Version: RFC 2965
String: CustomerID = 13xyz
*/

Remarks
The Cookies property provides an instance of the CookieCollection class that holds the cookies associated with this
response.
If the CookieContainer property of the associated HttpWebRequest is null , the Cookies property will also be null .
Any cookie information sent by the server will be available in the Headers property, however.
HttpWebResponse.Dispose HttpWebResponse.Dispose
I n this Article
Releases the unmanaged resources used by the HttpWebResponse, and optionally disposes of the managed resources.
protected override void Dispose (bool disposing);
override this.Dispose : bool -> unit

Parameters
disposing Boolean Boolean
true to release both managed and unmanaged resources; false to releases only unmanaged resources.

Remarks
This method is called by the public Dispose() method and the Finalize method. Dispose() invokes the protected
Dispose(Boolean) method with the disposing parameter set to true . Finalize invokes Dispose with disposing set
to false .
When the disposing parameter is true , this method releases all resources held by any managed objects that this
WebResponse references. This method invokes the Dispose() method of each referenced object.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
HttpWebResponse.GetHashCode HttpWebResponse.Get
HashCode
I n this Article
Returns a hash value for a HttpWebResponse instance.

public override int GetHashCode ();


override this.GetHashCode : unit -> int

Returns
Int32 Int32
An integer hash value.

Remarks
The GetHashCode method returns a hash code of the web response instance. This value can be used as a key in hash
tables.
HttpWebResponse.GetObjectData HttpWebResponse.
GetObjectData
I n this Article
Populates a SerializationInfo with the data needed to serialize the target object.

[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?


linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
protected override void GetObjectData (System.Runtime.Serialization.SerializationInfo
serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.
Attributes ObsoleteAttribute ObsoleteAttribute

Remarks
Any objects that are included in the SerializationInfo are automatically tracked and serialized by the formatter.
HttpWebResponse.GetResponseHeader HttpWeb
Response.GetResponseHeader
I n this Article
Gets the contents of a header that was returned with the response.

public string GetResponseHeader (string headerName);


member this.GetResponseHeader : string -> string

Parameters
headerName String String
The header value to return.
Returns
String String
The contents of the specified header.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
This example creates a Web request and queries for a response. If the site requires authentication, this example will
respond with a challenge string. This string is extracted using GetResponseHeader.
public static void GetPage(String url)
{
try
{
Uri ourUri = new Uri(url);
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
Console.WriteLine("
The server did not issue any challenge. Please try again with a protected resource URL.");
// Releases the resources of the response.
myHttpWebResponse.Close();
}
catch(WebException e)
{
HttpWebResponse response = (HttpWebResponse)e.Response;
if (response != null)
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
string challenge = null;
challenge= response.GetResponseHeader("WWW-Authenticate");
if (challenge != null)
Console.WriteLine("
The following challenge was raised by the server:{0}",challenge);
}
else
Console.WriteLine("
The following WebException was raised : {0}",e.Message);
}
else
Console.WriteLine("
Response Received from server was null");

}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}
}

Remarks
Use GetResponseHeader to retrieve the contents of particular headers. You must specify which header you want to
return.
HttpWebResponse.GetResponseStream HttpWeb
Response.GetResponseStream
I n this Article
Gets the stream that is used to read the body of the response from the server.

public override System.IO.Stream GetResponseStream ();


override this.GetResponseStream : unit -> System.IO.Stream

Returns
Stream Stream
A Stream containing the body of the response.
Exceptions
ProtocolViolationException ProtocolViolationException
There is no response stream.
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example demonstrates how to use GetResponseStream to return the Stream instance used to read the
response from the server.
// Creates an HttpWebRequest with the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Gets the stream associated with the response.
Stream receiveStream = myHttpWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipes the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( receiveStream, encode );
Console.WriteLine("\r
Response stream received.");
Char[] read = new Char[256];
// Reads 256 characters at a time.
int count = readStream.Read( read, 0, 256 );
Console.WriteLine("HTML...\r
");
while (count > 0)
{
// Dumps the 256 characters on a string and displays the string to the console.
String str = new String(read, 0, count);
Console.Write(str);
count = readStream.Read(read, 0, 256);
}
Console.WriteLine("");
// Releases the resources of the response.
myHttpWebResponse.Close();
// Releases the resources of the Stream.
readStream.Close();

Remarks
The GetResponseStream method returns the data stream from the requested Internet resource.
Note

You must call either the Stream.Close or the HttpWebResponse.Close method to close the stream and release the
connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not
cause an error. Failure to close the stream will cause your application to run out of connections.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
HttpWebResponse.Headers HttpWebResponse.Headers
I n this Article
Gets the headers that are associated with this response from the server.
public override System.Net.WebHeaderCollection Headers { get; }
member this.Headers : System.Net.WebHeaderCollection

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection that contains the header information returned with the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example writes the contents of all of the response headers to the console.
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

// Displays all the headers present in the response received from the URI.
Console.WriteLine("\r
The following headers were received in the response:");
// Displays each header and it's key associated with the response.
for(int i=0; i < myHttpWebResponse.Headers.Count; ++i)
Console.WriteLine("
Header Name:{0}, Value :{1}",myHttpWebResponse.Headers.Keys[i],myHttpWebResponse.Headers[i]);
// Releases the resources of the response.
myHttpWebResponse.Close();

Remarks
The Headers property is a collection of name/value pairs that contain the HTTP header values returned with the
response. Common header information returned from the Internet resource is exposed as properties of the
HttpWebResponse class. The following table lists common headers that the API exposes as properties.

HE AD ER PR O PER T Y

Content-Encoding ContentEncoding

Content-Length ContentLength

Content-Type ContentType

Last-Modified LastModified

Server Server
HttpWebResponse HttpWebResponse
I n this Article

Overloads
HttpWebResponse()
Initializes a new instance of the HttpWebResponse class.

HttpWebResponse(SerializationInfo, StreamingContext) Http


WebResponse(SerializationInfo, StreamingContext) Initializes a new instance of the HttpWebResponse class from
the specified SerializationInfo and StreamingContext instances.

HttpWebResponse()
Initializes a new instance of the HttpWebResponse class.
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public HttpWebResponse ();

Attributes ObsoleteAttribute

HttpWebResponse(SerializationInfo, StreamingContext)
HttpWebResponse(SerializationInfo, StreamingContext)
Initializes a new instance of the HttpWebResponse class from the specified SerializationInfo and StreamingContext
instances.
[System.Obsolete("Serialization is obsoleted for this type", false)]
[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?
linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
protected HttpWebResponse (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.HttpWebResponse : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.HttpWebResponse

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo that contains the information required to serialize the new HttpWebRequest.
streamingContext StreamingContext StreamingContext
A StreamingContext that contains the source of the serialized stream that is associated with the new HttpWebRequest.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Remarks
This constructor implements the ISerializable interface for the HttpWebRequest class.
See ISerializableISerializable
Also
HttpWebResponse.IDisposable.Dispose
I n this Article
Releases all resources used by the HttpWebResponse.
void IDisposable.Dispose ();

Remarks
Call Dispose when you are finished using the HttpWebResponse. The Dispose method leaves the HttpWebResponse
in an unusable state. After calling Dispose , you must release all references to the HttpWebResponse so the garbage
collector can reclaim the memory that the HttpWebResponse was occupying. For more information, see Cleaning Up
Unmanaged Resources and Implementing a Dispose Method.
Note

Always call Dispose before you release your last reference to the HttpWebResponse. Otherwise, the resources it is
using will not be freed until the garbage collector calls the HttpWebResponse object's Finalize method.
HttpWebResponse.ISerializable.GetObjectData
I n this Article
Serializes this instance into the specified SerializationInfo object.
[System.Obsolete("Serialization is obsoleted for this type. http://go.microsoft.com/fwlink/?
linkid=14202")]
[System.Obsolete("Serialization is obsoleted for this type. https://go.microsoft.com/fwlink/?
linkid=14202")]
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The object into which this HttpWebResponse will be serialized.
streamingContext StreamingContext
The destination of the serialization.
Attributes ObsoleteAttribute ObsoleteAttribute
HttpWebResponse.IsMutuallyAuthenticated HttpWeb
Response.IsMutuallyAuthenticated
I n this Article
Gets a Boolean value that indicates whether both client and server were authenticated.

public override bool IsMutuallyAuthenticated { get; }


member this.IsMutuallyAuthenticated : bool

Returns
Boolean Boolean
true if mutual authentication occurred; otherwise, false .

Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Remarks
You can specify mutual authentication using the AuthenticationLevel property.
HttpWebResponse.LastModified HttpWebResponse.Last
Modified
I n this Article
Gets the last date and time that the contents of the response were modified.

public DateTime LastModified { get; }


member this.LastModified : DateTime

Returns
DateTime DateTime
A DateTime that contains the date and time that the contents of the response were modified.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
This example creates an HttpWebRequest and queries for a response. This example then checks whether the entity
requested had been modified any time today.
Uri myUri = new Uri(url);
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
Console.WriteLine("\r
Request succeeded and the requested information is in the response , Description : {0}",
myHttpWebResponse.StatusDescription);
DateTime today = DateTime.Now;
// Uses the LastModified property to compare with today's date.
if (DateTime.Compare(today,myHttpWebResponse.LastModified) == 0)
Console.WriteLine("
The requested URI entity was modified today");
else
if (DateTime.Compare(today,myHttpWebResponse.LastModified) == 1)
Console.WriteLine("
The requested URI was last modified on:{0}",
myHttpWebResponse.LastModified);
// Releases the resources of the response.
myHttpWebResponse.Close();

Remarks
The LastModified property contains the value of the Last-Modified header received with the response. The date and
time are assumed to be local time.
HttpWebResponse.Method HttpWebResponse.Method
I n this Article
Gets the method that is used to return the response.
public virtual string Method { get; }
member this.Method : string

Returns
String String
A string that contains the HTTP method that is used to return the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example checks the string contained in Method, to determine the Http method invoked by the Web
server.
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
string method ;
method = myHttpWebResponse.Method;
if (String.Compare(method,"GET") == 0)
Console.WriteLine("
The 'GET' method was successfully invoked on the following Web Server : {0}",
myHttpWebResponse.Server);
// Releases the resources of the response.
myHttpWebResponse.Close();
}
catch(WebException e)
{
Console.WriteLine("
WebException raised. The following error occured : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
Method returns the method that is used to return the response. Common HTTP methods are GET, HEAD, POST, PUT,
and DELETE.
HttpWebResponse.ProtocolVersion HttpWebResponse.
ProtocolVersion
I n this Article
Gets the version of the HTTP protocol that is used in the response.

public Version ProtocolVersion { get; }


member this.ProtocolVersion : Version

Returns
Version Version
A Version that contains the HTTP protocol version of the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
This example creates an HttpWebRequest and queries for an HttpWebResponse. The example then checks to see if the
server is responding with the same version.
Uri ourUri = new Uri(url);
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(ourUri);
myHttpWebRequest.ProtocolVersion = HttpVersion.Version10;
// Sends the HttpWebRequest and waits for the response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
// Ensures that only Http/1.0 responses are accepted.
if(myHttpWebResponse.ProtocolVersion != HttpVersion.Version10)
Console.WriteLine("
The server responded with a version other than Http/1.0");
else
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
Console.WriteLine("
Request sent using version Http/1.0. Successfully received response with version HTTP/1.0 ");
// Releases the resources of the response.
myHttpWebResponse.Close();

Remarks
The ProtocolVersion property contains the HTTP protocol version number of the response sent by the Internet
resource.
HttpWebResponse.ResponseUri HttpWebResponse.
ResponseUri
I n this Article
Gets the URI of the Internet resource that responded to the request.

public override Uri ResponseUri { get; }


member this.ResponseUri : Uri

Returns
Uri Uri
The URI of the Internet resource that responded to the request.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
This example creates a HttpWebRequest and queries for an HttpWebResponse and then checks to see whether the
original URI was redirected by the server.
Uri myUri = new Uri(url);
// Create a 'HttpWebRequest' object for the specified url.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(myUri);
// Send the request and wait for response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
Console.WriteLine("
Request succeeded and the requested information is in the response ,Description : {0}",
myHttpWebResponse.StatusDescription);
if (myUri.Equals(myHttpWebResponse.ResponseUri))
Console.WriteLine("
The Request Uri was not redirected by the server");
else
Console.WriteLine("
The Request Uri was redirected to :{0}",myHttpWebResponse.ResponseUri);
// Release resources of response object.
myHttpWebResponse.Close();

Remarks
The ResponseUri property contains the URI of the Internet resource that actually responded to the request. This URI
might not be the same as the originally requested URI, if the original server redirected the request.
The ResponseUri property will use the Content-Location header if present.
Applications that need to access the last redirected ResponseUri should use the HttpWebRequest.Address property
rather than ResponseUri, since the use of ResponseUri property may open security vulnerabilities.
HttpWebResponse.Server HttpWebResponse.Server
I n this Article
Gets the name of the server that sent the response.
public string Server { get; }
member this.Server : string

Returns
String String
A string that contains the name of the server that sent the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example uses the Server property to display the Web server's name to the console.
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
string method ;
method = myHttpWebResponse.Method;
if (String.Compare(method,"GET") == 0)
Console.WriteLine("
The 'GET' method was successfully invoked on the following Web Server : {0}",
myHttpWebResponse.Server);
// Releases the resources of the response.
myHttpWebResponse.Close();
}
catch(WebException e)
{
Console.WriteLine("
WebException raised. The following error occured : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
The Server property contains the value of the Server header returned with the response.
HttpWebResponse.StatusCode HttpWebResponse.Status
Code
I n this Article
Gets the status of the response.

public virtual System.Net.HttpStatusCode StatusCode { get; }


member this.StatusCode : System.Net.HttpStatusCode

Returns
HttpStatusCode HttpStatusCode
One of the HttpStatusCode values.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example uses StatusCode to verify that the status of the HttpWebResponse is OK.
public static void GetPage(String url)
{
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for a response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
Console.WriteLine("\r
Response Status Code is OK and StatusDescription is: {0}",
myHttpWebResponse.StatusDescription);
// Releases the resources of the response.
myHttpWebResponse.Close();

}
catch(WebException e)
{
Console.WriteLine("\r
WebException Raised. The following error occured : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
The StatusCode parameter is a number that indicates the status of the HTTP response. The expected values for status
are defined in the HttpStatusCode class.
HttpWebResponse.StatusDescription HttpWebResponse.
StatusDescription
I n this Article
Gets the status description returned with the response.

public virtual string StatusDescription { get; }


member this.StatusDescription : string

Returns
String String
A string that describes the status of the response.
Exceptions
ObjectDisposedException ObjectDisposedException
The current instance has been disposed.

Examples
The following example uses StatusDescription to verify that the status of the HttpWebResponse is OK.
public static void GetPage(String url)
{
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
// Sends the HttpWebRequest and waits for a response.
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
Console.WriteLine("\r
Response Status Code is OK and StatusDescription is: {0}",
myHttpWebResponse.StatusDescription);
// Releases the resources of the response.
myHttpWebResponse.Close();

}
catch(WebException e)
{
Console.WriteLine("\r
WebException Raised. The following error occured : {0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("
The following Exception was raised : {0}",e.Message);
}
}

Remarks
A common status message is OK.
HttpWebResponse.SupportsHeaders HttpWebResponse.
SupportsHeaders
I n this Article
Gets a value that indicates whether headers are supported.

public override bool SupportsHeaders { get; }


member this.SupportsHeaders : bool

Returns
Boolean Boolean
true if headers are supported; otherwise, false . Always returns true .
IAuthenticationModule IAuthenticationModule Interface
Provides the base authentication interface for Web client authentication modules.

D eclaration
public interface IAuthenticationModule
type IAuthenticationModule = interface

I nheritance H ierarchy
None

Remarks
The IAuthenticationModule interface defines the properties and methods that custom authentication modules must
use.
Authentication modules conduct the entire authentication process with a server, responding to an authentication
challenge as appropriate. This process may consist of requests to an authentication server separate from the resource
server, as well as any other activities required to properly authenticate a request for a URI.
Custom authentication modules should implement the IAuthenticationModule interface and then register with the
AuthenticationManager.Register method. Authentication modules are also registered at program initialization by
reading the configuration file.

Properties
AuthenticationType
AuthenticationType

Gets the authentication type provided by this authentication module.

CanPreAuthenticate
CanPreAuthenticate

Gets a value indicating whether the authentication module supports preauthentication.

Methods
Authenticate(String, WebRequest, ICredentials)
Authenticate(String, WebRequest, ICredentials)

Returns an instance of the Authorization class in response to an authentication challenge from a server.

PreAuthenticate(WebRequest, ICredentials)
PreAuthenticate(WebRequest, ICredentials)

Returns an instance of the Authorization class for an authentication request to a server.


IAuthenticationModule.Authenticate IAuthentication
Module.Authenticate
I n this Article
Returns an instance of the Authorization class in response to an authentication challenge from a server.

public System.Net.Authorization Authenticate (string challenge, System.Net.WebRequest request,


System.Net.ICredentials credentials);
abstract member Authenticate : string * System.Net.WebRequest * System.Net.ICredentials ->
System.Net.Authorization

Parameters
challenge String String
The authentication challenge sent by the server.
request WebRequest WebRequest
The WebRequest instance associated with the challenge.
credentials ICredentials ICredentials
The credentials associated with the challenge.
Returns
Authorization Authorization
An Authorization instance containing the authorization message for the request, or null if the challenge cannot be
handled.

Examples
The following example shows how to use the Authenticate method. For a complete example refer to the
AuthenticationManager class.
// Authenticate is the core method for this custom authentication.
// When an Internet resource requests authentication, the WebRequest.GetResponse
// method calls the AuthenticationManager.Authenticate method. This method, in
// turn, calls the Authenticate method on each of the registered authentication
// modules, in the order in which they were registered. When the authentication is
// complete an Authorization object is returned to the WebRequest.
public Authorization Authenticate(String challenge, WebRequest request, ICredentials credentials)
{
Encoding ASCII = Encoding.ASCII;

// Get the username and password from the credentials


NetworkCredential MyCreds = credentials.GetCredential(request.RequestUri, "Basic");

if (PreAuthenticate(request, credentials) == null)


Console.WriteLine("
Pre-authentication is not allowed.");
else
Console.WriteLine("
Pre-authentication is allowed.");

// Verify that the challenge satisfies the authorization requirements.


bool challengeOk = checkChallenge(challenge, MyCreds.Domain);

if (!challengeOk)
return null;

// Create the encrypted string according to the Basic authentication format as


// follows:
// a)Concatenate the username and password separated by colon;
// b)Apply ASCII encoding to obtain a stream of bytes;
// c)Apply Base64 encoding to this array of bytes to obtain the encoded
// authorization.
string BasicEncrypt = MyCreds.UserName + ":" + MyCreds.Password;

string BasicToken = "Basic " + Convert.ToBase64String(ASCII.GetBytes(BasicEncrypt));

// Create an Authorization object using the encoded authorization above.


Authorization resourceAuthorization = new Authorization(BasicToken);

// Get the Message property, which contains the authorization string that the
// client returns to the server when accessing protected resources.
Console.WriteLine("
Authorization Message:{0}",resourceAuthorization.Message);

// Get the Complete property, which is set to true when the authentication process
// between the client and the server is finished.
Console.WriteLine("
Authorization Complete:{0}",resourceAuthorization.Complete);

Console.WriteLine("
Authorization ConnectionGroupId:{0}",resourceAuthorization.ConnectionGroupId);

return resourceAuthorization;
}

Remarks
The Authenticate method conducts the authentication process with the server and returns an Authorization instance to
the AuthenticationManager.
IAuthenticationModule.AuthenticationType I
AuthenticationModule.AuthenticationType
I n this Article
Gets the authentication type provided by this authentication module.

public string AuthenticationType { get; }


member this.AuthenticationType : string

Returns
String String
A string indicating the authentication type provided by this authentication module.

Examples
The following example shows how to use the AuthenticationType property. For a complete example refer to the
AuthenticationManager class.
private string m_authenticationType ;
private bool m_canPreAuthenticate ;

// The CustomBasic constructor initializes the properties of the customized


// authentication.
public CustomBasic()
{
m_authenticationType = "Basic";
m_canPreAuthenticate = false;
}

// Define the authentication type. This type is then used to identify this
// custom authentication module. The default is set to Basic.
public string AuthenticationType
{
get
{
return m_authenticationType;
}
}

// Define the pre-authentication capabilities for the module. The default is set
// to false.
public bool CanPreAuthenticate
{
get
{
return m_canPreAuthenticate;
}
}

Remarks
The AuthenticationType property identifies the authentication type implemented by this authentication module. The
AuthenticationType property is used by the AuthenticationManager.Register method to determine if the authentication
module has been registered, and by the AuthenticationManager.Unregister method to remove a registered
authentication module.
IAuthenticationModule.CanPreAuthenticate I
AuthenticationModule.CanPreAuthenticate
I n this Article
Gets a value indicating whether the authentication module supports preauthentication.

public bool CanPreAuthenticate { get; }


member this.CanPreAuthenticate : bool

Returns
Boolean Boolean
true if the authorization module supports preauthentication; otherwise false .

Examples
The following example shows how to use the CanPreAuthenticate property. For a complete example refer to the
AuthenticationManager class.
private string m_authenticationType ;
private bool m_canPreAuthenticate ;

// The CustomBasic constructor initializes the properties of the customized


// authentication.
public CustomBasic()
{
m_authenticationType = "Basic";
m_canPreAuthenticate = false;
}

// Define the authentication type. This type is then used to identify this
// custom authentication module. The default is set to Basic.
public string AuthenticationType
{
get
{
return m_authenticationType;
}
}

// Define the pre-authentication capabilities for the module. The default is set
// to false.
public bool CanPreAuthenticate
{
get
{
return m_canPreAuthenticate;
}
}

Remarks
The CanPreAuthenticate property is set to true to indicate that the authentication module can respond with a valid
Authorization instance when the PreAuthenticate method is called.
IAuthenticationModule.PreAuthenticate IAuthentication
Module.PreAuthenticate
I n this Article
Returns an instance of the Authorization class for an authentication request to a server.

public System.Net.Authorization PreAuthenticate (System.Net.WebRequest request,


System.Net.ICredentials credentials);
abstract member PreAuthenticate : System.Net.WebRequest * System.Net.ICredentials ->
System.Net.Authorization

Parameters
request WebRequest WebRequest
The WebRequest instance associated with the authentication request.
credentials ICredentials ICredentials
The credentials associated with the authentication request.
Returns
Authorization Authorization
An Authorization instance containing the authorization message for the request.

Examples
The following example shows how to use the PreAuthenticate method. For a complete example refer to the
AuthenticationManager class.

// The PreAuthenticate method specifies whether the authentication implemented


// by this class allows pre-authentication.
// Even if you do not use it, this method must be implemented to obey to the rules
// of interface implementation.
// In this case it always returns null.
public Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
{
return null;
}

Remarks
When the CanPreAuthenticate property is true , the PreAuthenticate method will return an instance of the
Authorization class containing an authentication message.
ICertificatePolicy ICertificatePolicy Interface
Validates a server certificate.

D eclaration
public interface ICertificatePolicy
type ICertificatePolicy = interface

I nheritance H ierarchy
None

Remarks
The ICertificatePolicy interface is used to provide custom security certificate validation for an application. The default
policy is to allow valid certificates, as well as valid certificates that have expired. To change this policy, implement the
ICertificatePolicy interface with a different policy, and then assign that policy to ServicePointManager.CertificatePolicy.
ICertificatePolicy uses the Security Support Provider Interface (SSPI). For more information, see the SSPI
documentation on MSDN.

Methods
CheckValidationResult(ServicePoint, X509Certificate, WebRequest, Int32)
CheckValidationResult(ServicePoint, X509Certificate, WebRequest, Int32)

Validates a server certificate.


ICertificatePolicy.CheckValidationResult ICertificatePolicy.
CheckValidationResult
I n this Article
Validates a server certificate.

public bool CheckValidationResult (System.Net.ServicePoint srvPoint,


System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Net.WebRequest
request, int certificateProblem);
abstract member CheckValidationResult : System.Net.ServicePoint *
System.Security.Cryptography.X509Certificates.X509Certificate * System.Net.WebRequest * int -> bool

Parameters
srvPoint ServicePoint ServicePoint
The ServicePoint that will use the certificate.
certificate X509Certificate X509Certificate
The certificate to validate.
request WebRequest WebRequest
The request that received the certificate.
certificateProblem Int32 Int32
The problem that was encountered when using the certificate.
Returns
Boolean Boolean
true if the certificate should be honored; otherwise, false .

Remarks
The CheckValidationResult method implements the application certificate validation policy. The method can examine
the srvPoint , certificate , request , and certificateProblem parameters to determine whether the certificate
should be honored.
The certificateProblem parameter is a Security Support Provider Interface (SSPI) status code. For more
information, see the SSPI documentation on MSDN.
ICredentialPolicy ICredentialPolicy Interface
Defines the credential policy to be used for resource requests that are made using WebRequest and its derived classes.

D eclaration
public interface ICredentialPolicy
type ICredentialPolicy = interface

I nheritance H ierarchy
None

Remarks
The credential policy determines whether to send credentials when sending a WebRequest for a network resource,
such as the content of a Web page. If credentials are sent, servers that require client authentication can attempt to
authenticate the client when the request is received instead of sending a response that indicates that the client's
credentials are required. While this saves a round trip to the server, this performance gain must be balanced against the
security risk inherent in sending credentials across the network. When the destination server does not require client
authentication, it is best not to send credentials.
Note

ICredentialPolicy policies are invoked only if the WebRequest or the WebProxy that is associated with the request has
credentials that are not null . Setting this policy has no effect on requests that do not specify credentials.
Use the AuthenticationManager.CredentialPolicy property to set an ICredentialPolicy policy. The
IAuthenticationModule that handles authentication for the request will invoke the ShouldSendCredential method
before performing the authentication. If the method returns false , authentication is not performed.
An ICredentialPolicy policy affects all instances of WebRequest with non-null credentials in the current application
domain. The policy cannot be overridden on individual requests.

Methods
ShouldSendCredential(Uri, WebRequest, NetworkCredential, IAuthenticationModule)
ShouldSendCredential(Uri, WebRequest, NetworkCredential, IAuthenticationModule)

Returns a Boolean that indicates whether the client's credentials are sent with a resource request made using an
instance of the WebRequest class.
ICredentialPolicy.ShouldSendCredential ICredentialPolicy.
ShouldSendCredential
I n this Article
Returns a Boolean that indicates whether the client's credentials are sent with a resource request made using an
instance of the WebRequest class.
public bool ShouldSendCredential (Uri challengeUri, System.Net.WebRequest request,
System.Net.NetworkCredential credential, System.Net.IAuthenticationModule authenticationModule);
abstract member ShouldSendCredential : Uri * System.Net.WebRequest * System.Net.NetworkCredential *
System.Net.IAuthenticationModule -> bool

Parameters
challengeUri Uri Uri
The Uri that will receive the request.
request WebRequest WebRequest
The WebRequest that represents the resource being requested.
credential NetworkCredential NetworkCredential
The NetworkCredential that will be sent with the request if this method returns true .
authenticationModule IAuthenticationModule IAuthenticationModule
The IAuthenticationModule that will conduct the authentication, if authentication is required.
Returns
Boolean Boolean
true if the credentials are sent with the request; otherwise, false .

Remarks
After an ICredentialPolicy policy has been specified by setting the AuthenticationManager.CredentialPolicy property,
the IAuthenticationModule that handles authentication for a WebRequest invokes the ShouldSendCredential method
before performing the authentication. If this method returns false , authentication is not performed.
When the original request has been redirected or proxy authentication is required, the resource identified by
challengeUri can be different from the requested resource that is specified in WebRequest.RequestUri. In the case of
redirection, challengeUri contains the actual destination Uri. If proxy authentication is required, challengeUri
contains the address of the proxy server that requires client authentication.
ICredentials ICredentials Interface
Provides the base authentication interface for retrieving credentials for Web client authentication.

D eclaration
public interface ICredentials
type ICredentials = interface

I nheritance H ierarchy
None

Remarks
The ICredentials interface provides the GetCredential method to objects that supply network credentials to
applications.

Methods
GetCredential(Uri, String)
GetCredential(Uri, String)

Returns a NetworkCredential object that is associated with the specified URI, and authentication type.
ICredentials.GetCredential ICredentials.GetCredential
I n this Article
Returns a NetworkCredential object that is associated with the specified URI, and authentication type.
public System.Net.NetworkCredential GetCredential (Uri uri, string authType);
abstract member GetCredential : Uri * string -> System.Net.NetworkCredential

Parameters
uri Uri Uri
The Uri that the client is providing authentication for.
authType String String
The type of authentication, as defined in the AuthenticationType property.
Returns
NetworkCredential NetworkCredential
The NetworkCredential that is associated with the specified URI and authentication type, or, if no credentials are
available, null .

Examples
The following uses GetCredential to retrieve a NetworkCredential instance.
class CredentialList : ICredentials
{
class CredentialInfo
{
public Uri uriObj;
public String authenticationType;
public NetworkCredential networkCredentialObj;

public CredentialInfo(Uri uriObj, String authenticationType, NetworkCredential


networkCredentialObj)
{
this.uriObj = uriObj;
this.authenticationType = authenticationType;
this.networkCredentialObj = networkCredentialObj;
}
}

private ArrayList arrayListObj;

public CredentialList()
{
arrayListObj = new ArrayList();
}

public void Add (Uri uriObj, String authenticationType, NetworkCredential credential)


{
// Add a 'CredentialInfo' object into a list.
arrayListObj.Add (new CredentialInfo(uriObj, authenticationType, credential));
}
// Remove the 'CredentialInfo' object from the list that matches to the given 'Uri' and
'AuthenticationType'
public void Remove (Uri uriObj, String authenticationType)
{
for(int index=0;index < arrayListObj.Count; index++)
{
CredentialInfo credentialInfo = (CredentialInfo)arrayListObj[index];
if(uriObj.Equals(credentialInfo.uriObj)&&
authenticationType.Equals(credentialInfo.authenticationType))
arrayListObj.RemoveAt(index);
}
}
public NetworkCredential GetCredential (Uri uriObj, String authenticationType)
{
for(int index=0;index < arrayListObj.Count; index++)
{
CredentialInfo credentialInfoObj = (CredentialInfo)arrayListObj[index];
if(uriObj.Equals(credentialInfoObj.uriObj) &&
authenticationType.Equals(credentialInfoObj.authenticationType))
return credentialInfoObj.networkCredentialObj;
}
return null;
}
};

Remarks
The GetCredential method returns a NetworkCredential instance that contains the credentials that are associated with
the specified URI and authorization scheme. When no credentials are available, the GetCredential method returns
null .
ICredentialsByHost ICredentialsByHost Interface
Provides the interface for retrieving credentials for a host, port, and authentication type.

D eclaration
public interface ICredentialsByHost
type ICredentialsByHost = interface

I nheritance H ierarchy
None

Remarks
The credentials are used for authentication of requests sent to hosts using the WebClient class, and WebRequest and
its derived classes.

Methods
GetCredential(String, Int32, String)
GetCredential(String, Int32, String)

Returns the credential for the specified host, port, and authentication protocol.
ICredentialsByHost.GetCredential ICredentialsByHost.Get
Credential
I n this Article
Returns the credential for the specified host, port, and authentication protocol.

public System.Net.NetworkCredential GetCredential (string host, int port, string


authenticationType);
abstract member GetCredential : string * int * string -> System.Net.NetworkCredential

Parameters
host String String
The host computer that is authenticating the client.
port Int32 Int32
The port on host that the client will communicate with.
authenticationType String String
The authentication protocol.
Returns
NetworkCredential NetworkCredential
A NetworkCredential for the specified host, port, and authentication protocol, or null if there are no credentials
available for the specified host, port, and authentication protocol.

Remarks
The value of authType corresponds to the IAuthenticationModule.AuthenticationType property.
INetworkProgress INetworkProgress Interface
Provides information on network progress in sending data over the network.

D eclaration
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be
used directly from your code.", true)]
public interface INetworkProgress
type INetworkProgress = interface

I nheritance H ierarchy
None

Events
ProgressChanged
ProgressChanged

Network progress has changed.

ProgressCompleted
ProgressCompleted

Network progress has completed.

ProgressFailed
ProgressFailed

Network progress has failed.


INetworkProgress.ProgressChanged INetworkProgress.
ProgressChanged
I n this Article
Network progress has changed.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
event EventHandler<System.Net.NetworkProgressChangedEventArgs> ProgressChanged;
member this.ProgressChanged : EventHandler<System.Net.NetworkProgressChangedEventArgs>

Attributes ObsoleteAttribute
INetworkProgress.ProgressCompleted INetworkProgress.
ProgressCompleted
I n this Article
Network progress has completed.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
event EventHandler<System.Net.NetworkProgressChangedEventArgs> ProgressCompleted;
member this.ProgressCompleted : EventHandler<System.Net.NetworkProgressChangedEventArgs>

Attributes ObsoleteAttribute
INetworkProgress.ProgressFailed INetworkProgress.
ProgressFailed
I n this Article
Network progress has failed.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
event EventHandler<System.Net.NetworkProgressChangedEventArgs> ProgressFailed;
member this.ProgressFailed : EventHandler<System.Net.NetworkProgressChangedEventArgs>

Attributes ObsoleteAttribute
IPAddress IPAddress Class
Provides an Internet Protocol (IP ) address.

D eclaration
[System.Serializable]
public class IPAddress
type IPAddress = class

I nheritance H ierarchy
Object Object

Remarks
The IPAddress class contains the address of a computer on an IP network.

Constructors
IPAddress(Byte[])
IPAddress(Byte[])

Initializes a new instance of the IPAddress class with the address specified as a Byte array.

IPAddress(Int64)
IPAddress(Int64)

Initializes a new instance of the IPAddress class with the address specified as an Int64.

IPAddress(ReadOnlySpan<Byte>)
IPAddress(ReadOnlySpan<Byte>)

IPAddress(Byte[], Int64)
IPAddress(Byte[], Int64)

Initializes a new instance of the IPAddress class with the address specified as a Byte array and the specified scope
identifier.

IPAddress(ReadOnlySpan<Byte>, Int64)
IPAddress(ReadOnlySpan<Byte>, Int64)

Fields
Any
Any
Provides an IP address that indicates that the server must listen for client activity on all network interfaces. This
field is read-only.

Broadcast
Broadcast

Provides the IP broadcast address. This field is read-only.

IPv6Any
IPv6Any

The Bind(EndPoint) method uses the IPv6Any field to indicate that a Socket must listen for client activity on all
network interfaces.

IPv6Loopback
IPv6Loopback

Provides the IP loopback address. This property is read-only.

IPv6None
IPv6None

Provides an IP address that indicates that no network interface should be used. This property is read-only.

Loopback
Loopback

Provides the IP loopback address. This field is read-only.

None
None

Provides an IP address that indicates that no network interface should be used. This field is read-only.

Properties
Address
Address

An Internet Protocol (IP ) address.

AddressFamily
AddressFamily

Gets the address family of the IP address.


IsIPv4MappedToIPv6
IsIPv4MappedToIPv6

Gets whether the IP address is an IPv4-mapped IPv6 address.

IsIPv6LinkLocal
IsIPv6LinkLocal

Gets whether the address is an IPv6 link local address.

IsIPv6Multicast
IsIPv6Multicast

Gets whether the address is an IPv6 multicast global address.

IsIPv6SiteLocal
IsIPv6SiteLocal

Gets whether the address is an IPv6 site local address.

IsIPv6Teredo
IsIPv6Teredo

Gets whether the address is an IPv6 Teredo address.

ScopeId
ScopeId

Gets or sets the IPv6 address scope identifier.

Methods
Equals(Object)
Equals(Object)

Compares two IP addresses.

GetAddressBytes()
GetAddressBytes()

Provides a copy of the IPAddress as an array of bytes.

GetHashCode()
GetHashCode()

Returns a hash value for an IP address.


HostToNetworkOrder(Int16)
HostToNetworkOrder(Int16)

Converts a short value from host byte order to network byte order.

HostToNetworkOrder(Int32)
HostToNetworkOrder(Int32)

Converts an integer value from host byte order to network byte order.

HostToNetworkOrder(Int64)
HostToNetworkOrder(Int64)

Converts a long value from host byte order to network byte order.

IsLoopback(IPAddress)
IsLoopback(IPAddress)

Indicates whether the specified IP address is the loopback address.

MapToIPv4()
MapToIPv4()

Maps the IPAddress object to an IPv4 address.

MapToIPv6()
MapToIPv6()

Maps the IPAddress object to an IPv6 address.

NetworkToHostOrder(Int32)
NetworkToHostOrder(Int32)

Converts an integer value from network byte order to host byte order.

NetworkToHostOrder(Int64)
NetworkToHostOrder(Int64)

Converts a long value from network byte order to host byte order.

NetworkToHostOrder(Int16)
NetworkToHostOrder(Int16)

Converts a short value from network byte order to host byte order.
Parse(ReadOnlySpan<Char>)
Parse(ReadOnlySpan<Char>)

Parse(String)
Parse(String)

Converts an IP address string to an IPAddress instance.

ToString()
ToString()

Converts an Internet address to its standard notation.

TryFormat(Span<Char>, Int32)
TryFormat(Span<Char>, Int32)

TryParse(String, IPAddress)
TryParse(String, IPAddress)

Determines whether a string is a valid IP address.

TryParse(ReadOnlySpan<Char>, IPAddress)
TryParse(ReadOnlySpan<Char>, IPAddress)

TryWriteBytes(Span<Byte>, Int32)
TryWriteBytes(Span<Byte>, Int32)
IPAddress.Address IPAddress.Address
I n this Article
An Internet Protocol (IP ) address.
[System.Obsolete("This property has been deprecated. It is address family dependent. Please use
IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("IPAddress.Address is address family dependant, use Equals method for
comparison.")]
[System.Obsolete("This property has been deprecated. It is address family dependent. Please use
IPAddress.Equals method to perform comparisons. https://go.microsoft.com/fwlink/?linkid=14202")]
public long Address { get; set; }
member this.Address : int64 with get, set

Returns
Int64 Int64
The long value of the IP address.
Attributes ObsoleteAttribute ObsoleteAttribute ObsoleteAttribute
Exceptions
SocketException SocketException
The address family is InterNetworkV6.

Remarks
This property is obsolete. Use GetAddressBytes.
To convert Address to dotted-quad notation, use the ToString method.
IPAddress.AddressFamily IPAddress.AddressFamily
I n this Article
Gets the address family of the IP address.
public System.Net.Sockets.AddressFamily AddressFamily { get; }
member this.AddressFamily : System.Net.Sockets.AddressFamily

Returns
AddressFamily AddressFamily
Returns InterNetwork for IPv4 or InterNetworkV6 for IPv6.

Examples
Refer to the example in the IPAddress class topic.

// Display the type of address family supported by the server. If the


// server is IPv6-enabled this value is: InterNetworkV6. If the server
// is also IPv4-enabled there will be an additional value of InterNetwork.
Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());

// Display the ScopeId property in case of IPV6 addresses.


if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());
IPAddress.Any IPAddress.Any
I n this Article
Provides an IP address that indicates that the server must listen for client activity on all network interfaces. This field is
read-only.

public static readonly System.Net.IPAddress Any;


staticval mutable Any : System.Net.IPAddress

Returns
IPAddress IPAddress

Remarks
The Socket.Bind method uses the Any field to indicate that a Socket instance must listen for client activity on all
network interfaces.
The Any field is equivalent to 0.0.0.0 in dotted-quad notation.
IPAddress.Broadcast IPAddress.Broadcast
I n this Article
Provides the IP broadcast address. This field is read-only.
public static readonly System.Net.IPAddress Broadcast;
staticval mutable Broadcast : System.Net.IPAddress

Returns
IPAddress IPAddress

Examples
The following example prints the Broadcast address to the console.

public void PrintBroadcastAddress()


{
// Get the IP Broadcast address and convert it to string.
string ipAddressString = IPAddress.Broadcast.ToString();
Console.WriteLine("Broadcast IP address: {0}", ipAddressString);
}

Remarks
The Broadcast field is equivalent to 255.255.255.255 in dotted-quad notation.
IPAddress.Equals IPAddress.Equals
I n this Article
Compares two IP addresses.
public override bool Equals (object comparand);
override this.Equals : obj -> bool

Parameters
comparand Object Object
An IPAddress instance to compare to the current instance.
Returns
Boolean Boolean
true if the two addresses are equal; otherwise, false .

Remarks
The Equals method compares the current IPAddress instance with the comparand parameter and returns true if the
two instances contain the same IP address.
IPAddress.GetAddressBytes IPAddress.GetAddressBytes
I n this Article
Provides a copy of the IPAddress as an array of bytes.
public byte[] GetAddressBytes ();
member this.GetAddressBytes : unit -> byte[]

Returns
Byte[]
A Byte array.

Examples
The following code example shows how to get a server IP address in byte format.
Byte[] bytes = curAdd.GetAddressBytes();
for (int i = 0; i < bytes.Length; i++)
{
Console.Write(bytes[i]);
}
IPAddress.GetHashCode IPAddress.GetHashCode
I n this Article
Returns a hash value for an IP address.
public override int GetHashCode ();
override this.GetHashCode : unit -> int

Returns
Int32 Int32
An integer hash value.

Remarks
The GetHashCode method returns a hash code of the IP address. This value can be used as a key in hash tables.
IPAddress.HostToNetworkOrder IPAddress.HostTo
NetworkOrder
I n this Article

Overloads
HostToNetworkOrder(Int16) HostToNetworkOrder(Int16)
Converts a short value from host byte order to network byte
order.

HostToNetworkOrder(Int32) HostToNetworkOrder(Int32)
Converts an integer value from host byte order to network
byte order.

HostToNetworkOrder(Int64) HostToNetworkOrder(Int64)
Converts a long value from host byte order to network byte
order.

HostToNetworkOrder(Int16) HostToNetworkOrder(Int16)
Converts a short value from host byte order to network byte order.
public static short HostToNetworkOrder (short host);
static member HostToNetworkOrder : int16 -> int16

Parameters
host Int16 Int16
The number to convert, expressed in host byte order.
Returns
Int16 Int16
A short value, expressed in network byte order.
Remarks
Different computers use different conventions for ordering the bytes within multibyte integer values. Some computers
put the most significant byte first (known as big-endian order) and others put the least-significant byte first (known as
little-endian order). To work with computers that use different byte ordering, all integer values that are sent over the
network are sent in network byte order which has the most significant byte first.
The HostToNetworkOrder method converts multibyte integer values that are stored on the host system from the byte
order used by the host to the byte order used by the network.
See NetworkToHostOrder(Int64)NetworkToHostOrder(Int64)
Also

HostToNetworkOrder(Int32) HostToNetworkOrder(Int32)
Converts an integer value from host byte order to network byte order.
public static int HostToNetworkOrder (int host);
static member HostToNetworkOrder : int -> int

Parameters
host Int32 Int32
The number to convert, expressed in host byte order.
Returns
Int32 Int32
An integer value, expressed in network byte order.
Remarks
Different computers use different conventions for ordering the bytes within multibyte integer values. Some computers
put the most significant byte first (known as big-endian order) and others put the least-significant byte first (known as
little-endian order). To work with computers that use different byte ordering, all integer values that are sent over the
network are sent in network byte order which has the most significant byte first.
The HostToNetworkOrder method converts multibyte integer values that are stored on the host system from the byte
order used by the host to the byte order used by the network.
See NetworkToHostOrder(Int64)NetworkToHostOrder(Int64)
Also

HostToNetworkOrder(Int64) HostToNetworkOrder(Int64)
Converts a long value from host byte order to network byte order.

public static long HostToNetworkOrder (long host);


static member HostToNetworkOrder : int64 -> int64

Parameters
host Int64 Int64
The number to convert, expressed in host byte order.
Returns
Int64 Int64
A long value, expressed in network byte order.
Remarks
Different computers use different conventions for ordering the bytes within multibyte integer values. Some computers
put the most significant byte first (known as big-endian order) and others put the least-significant byte first (known as
little-endian order). To work with computers that use different byte ordering, all integer values that are sent over the
network are sent in network byte order which has the most significant byte first.
The HostToNetworkOrder method converts multibyte integer values that are stored on the host system from the byte
order used by the host to the byte order used by the network.
See NetworkToHostOrder(Int64)NetworkToHostOrder(Int64)
Also
IPAddress IPAddress
I n this Article

Overloads
IPAddress(Byte[]) IPAddress(Byte[])
Initializes a new instance of the IPAddress class with the
address specified as a Byte array.

IPAddress(Int64) IPAddress(Int64)
Initializes a new instance of the IPAddress class with the
address specified as an Int64.

IPAddress(ReadOnlySpan<Byte>) IPAddress(ReadOnlySpan<Byte>)

IPAddress(Byte[], Int64) IPAddress(Byte[], Int64)


Initializes a new instance of the IPAddress class with the
address specified as a Byte array and the specified scope
identifier.

IPAddress(ReadOnlySpan<Byte>, Int64) IPAddress(ReadOnlySpan<Byte>, Int64)

IPAddress(Byte[]) IPAddress(Byte[])
Initializes a new instance of the IPAddress class with the address specified as a Byte array.
public IPAddress (byte[] address);
new System.Net.IPAddress : byte[] -> System.Net.IPAddress

Parameters
address Byte[]
The byte array value of the IP address.
Exceptions
ArgumentNullException ArgumentNullException
address is null .
ArgumentException ArgumentException
address contains a bad IP address.
Remarks
The IPAddress is created with the Address property set to address .
If the length of address is 4, IPAddress(Byte[]) constructs an IPv4 address; otherwise, an IPv6 address with a scope of
0 is constructed.
The Byte array is assumed to be in network byte order with the most significant byte first in index position 0.

IPAddress(Int64) IPAddress(Int64)
Initializes a new instance of the IPAddress class with the address specified as an Int64.
public IPAddress (long newAddress);
new System.Net.IPAddress : int64 -> System.Net.IPAddress

Parameters
newAddress Int64 Int64
The long value of the IP address. For example, the value 0x2414188f in big-endian format would be the IP address
"143.24.20.36".
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
newAddress < 0 or
newAddress > 0x00000000FFFFFFFF
Remarks
The IPAddress instance is created with the Address property set to newAddress .
The Int64 value is assumed to be in network byte order.

IPAddress(ReadOnlySpan<Byte>)
IPAddress(ReadOnlySpan<Byte>)
public IPAddress (ReadOnlySpan<byte> address);
new System.Net.IPAddress : ReadOnlySpan<byte> -> System.Net.IPAddress

Parameters
address ReadOnlySpan<Byte>

IPAddress(Byte[], Int64) IPAddress(Byte[], Int64)


Initializes a new instance of the IPAddress class with the address specified as a Byte array and the specified scope
identifier.
public IPAddress (byte[] address, long scopeid);
new System.Net.IPAddress : byte[] * int64 -> System.Net.IPAddress

Parameters
address Byte[]
The byte array value of the IP address.
scopeid Int64 Int64
The long value of the scope identifier.
Exceptions
ArgumentNullException ArgumentNullException
address is null .
ArgumentException ArgumentException
address contains a bad IP address.
ArgumentOutOfRangeException ArgumentOutOfRangeException
scopeid < 0 or

scopeid > 0x00000000FFFFFFFF


Remarks
This constructor instantiates an IPv6 address. The scopeid identifies a network interface in the case of a link-local
address. The scope is valid only for link-local and site-local addresses.
The Byte array is assumed to be in network byte order with the most significant byte first in index position 0.

IPAddress(ReadOnlySpan<Byte>, Int64)
IPAddress(ReadOnlySpan<Byte>, Int64)
public IPAddress (ReadOnlySpan<byte> address, long scopeid);
new System.Net.IPAddress : ReadOnlySpan<byte> * int64 -> System.Net.IPAddress

Parameters
address ReadOnlySpan<Byte>
scopeid Int64 Int64
IPAddress.IPv6Any IPAddress.IPv6Any
I n this Article
The Bind(EndPoint) method uses the IPv6Any field to indicate that a Socket must listen for client activity on all network
interfaces.

public static readonly System.Net.IPAddress IPv6Any;


staticval mutable IPv6Any : System.Net.IPAddress

Returns
IPAddress IPAddress

Examples
The following code example displays the value of the current host's Any address in standard compressed format.
// This method displays the value of the current host's Any address in
// standard compressed format. The Any address is used by the host to enable
// listening to client activities on all the interfaces for a given port.
private static void displayIPv6AnyAddress()
{
try
{
// Get the Any address.
IPAddress any = IPAddress.IPv6Any;

// Transform the Any address to a string using the overloaded


// ToString() method. Note that the resulting string is in the compact
// form: "::".
string ipv6Any = any.ToString();

// Display the Any address.


Console.WriteLine("The IPv6 Any address is: " + ipv6Any);
}
catch (Exception e)
{
Console.WriteLine("[displayIPv6AnyAddress] Exception: " + e.ToString());
}
}

Remarks
The IPv6Any field is equivalent to 0:0:0:0:0:0:0:0 in colon-hexadecimal notation, or to :: in compact notation.
IPAddress.IPv6Loopback IPAddress.IPv6Loopback
I n this Article
Provides the IP loopback address. This property is read-only.
public static readonly System.Net.IPAddress IPv6Loopback;
staticval mutable IPv6Loopback : System.Net.IPAddress

Returns
IPAddress IPAddress

Examples
The following code example displays the value of the current host's loopback address in standard compressed format.

// This method displays the value of the current host loopback address in
// standard compressed format.
private static void displayIPv6LoopBackAddress()
{
try
{
// Get the loopback address.
IPAddress loopBack = IPAddress.IPv6Loopback;

// Transform the loop-back address to a string using the overladed


// ToString() method. Note that the resulting string is in the compact
// form: "::1".
string ipv6LoopBack = loopBack.ToString();
Console.WriteLine("The IPv6 Loopback address is: " + ipv6LoopBack);
}
catch (Exception e)
{
Console.WriteLine("[displayIPv6LoopBackAddress] Exception: " + e.ToString());
}
}

Remarks
The IPv6Loopback field is equivalent to 0:0:0:0:0:0:0:1 in colon-hexadecimal notation, or to ::1 in compact notation.
IPAddress.IPv6None IPAddress.IPv6None
I n this Article
Provides an IP address that indicates that no network interface should be used. This property is read-only.
public static readonly System.Net.IPAddress IPv6None;
staticval mutable IPv6None : System.Net.IPAddress

Returns
IPAddress IPAddress

Examples
The following code example displays the value of the current host's None address in standard compressed format.

// This method displays the value of the current host's None address in
// standard compressed format. The None address is used by the host to disable
// listening to client activities on all the interfaces.
private static void displayIPv6NoneAddress()
{
try
{

// Get the None address.


IPAddress none = IPAddress.IPv6None;

// Transform the None address to a string using the overloaded


// ToString() method. Note that the resulting string is in the compact
// form: "::".
string ipv6None = none.ToString();

Console.WriteLine("The IPv6 None address is: " + ipv6None);


}
catch (Exception e)
{
Console.WriteLine("[displayIPv6NoneAddress] Exception: " + e.ToString());
}
}

Remarks
The Socket.Bind method uses the IPv6None field to indicate that a Socket must not listen for client activity. The
IPv6None field is equivalent to 0:0:0:0:0:0:0:0 in colon-hexadecimal notation, or to ::0 in compact notation.
IPAddress.IsIPv4MappedToIPv6 IPAddress.IsIPv4Mapped
ToIPv6
I n this Article
Gets whether the IP address is an IPv4-mapped IPv6 address.

public bool IsIPv4MappedToIPv6 { get; }


member this.IsIPv4MappedToIPv6 : bool

Returns
Boolean Boolean
Returns Boolean.
true if the IP address is an IPv4-mapped IPv6 address; otherwise, false .

Remarks
Dual-stack sockets always require IPv6 addresses. The ability to interact with an IPv4 address requires the use of the
IPv4-mapped IPv6 address format. Any IPv4 addresses must be represented in the IPv4-mapped IPv6 address format
which enables an IPv6 only application to communicate with an IPv4 node. The IPv4-mapped IPv6 address format
allows the IPv4 address of an IPv4 node to be represented as an IPv6 address. The IPv4 address is encoded into the
low -order 32 bits of the IPv6 address, and the high-order 96 bits hold the fixed prefix 0:0:0:0:0:FFFF. The IPv4-mapped
IPv6 address format is specified in RFC 4291. For more information, see www.ietf.org/rfc/rfc4291.txt.
IPAddress.IsIPv6LinkLocal IPAddress.IsIPv6LinkLocal
I n this Article
Gets whether the address is an IPv6 link local address.
public bool IsIPv6LinkLocal { get; }
member this.IsIPv6LinkLocal : bool

Returns
Boolean Boolean
true if the IP address is an IPv6 link local address; otherwise, false .
IPAddress.IsIPv6Multicast IPAddress.IsIPv6Multicast
I n this Article
Gets whether the address is an IPv6 multicast global address.
public bool IsIPv6Multicast { get; }
member this.IsIPv6Multicast : bool

Returns
Boolean Boolean
true if the IP address is an IPv6 multicast global address; otherwise, false .
IPAddress.IsIPv6SiteLocal IPAddress.IsIPv6SiteLocal
I n this Article
Gets whether the address is an IPv6 site local address.
public bool IsIPv6SiteLocal { get; }
member this.IsIPv6SiteLocal : bool

Returns
Boolean Boolean
true if the IP address is an IPv6 site local address; otherwise, false .
IPAddress.IsIPv6Teredo IPAddress.IsIPv6Teredo
I n this Article
Gets whether the address is an IPv6 Teredo address.
public bool IsIPv6Teredo { get; }
member this.IsIPv6Teredo : bool

Returns
Boolean Boolean
true if the IP address is an IPv6 Teredo address; otherwise, false .

Remarks
A Teredo address is an IPv6 address with the prefix of 2001::/32. Teredo addresses can be returned through normal
DNS name resolution or enumerated as an IPv6 address assigned to a local interface.
IPAddress.IsLoopback IPAddress.IsLoopback
I n this Article
Indicates whether the specified IP address is the loopback address.
public static bool IsLoopback (System.Net.IPAddress address);
static member IsLoopback : System.Net.IPAddress -> bool

Parameters
address IPAddress IPAddress
An IP address.
Returns
Boolean Boolean
true if address is the loopback address; otherwise, false .

Examples
The following code example uses the IsLoopback method to determine whether the specified address is a loopback
address.

using System;
using System.Net;
using System.Net.Sockets;

class IsLoopbackTest
{

private static void Main(string[] args)


{

if (args.Length == 0)
{
// No parameters entered. Display program usage.
Console.WriteLine("Please enter an IP address.");
Console.WriteLine("Usage: >ipaddress_isloopback any IPv4 or IPv6 address.");
Console.WriteLine("Example: >ipaddress_isloopback 127.0.0.1");
Console.WriteLine("Example: >ipaddress_isloopback 0:0:0:0:0:0:0:1");
return;
}
else
// Parse the address string entered by the user.
parse(args[0]);

// This method calls the IPAddress.Parse method to check if the


// passed ipAddress parameter is in the correct format.
// Then it checks whether it represents a loopback address.
// Finally, it displays the results.
private static void parse(string ipAddress)
{
string loopBack=" is not a loopback address.";

try
{
// Perform syntax check by parsing the address string entered by the user.
// Perform syntax check by parsing the address string entered by the user.
IPAddress address = IPAddress.Parse(ipAddress);

// Perform semantic check by verifying that the address is a valid IPv4


// or IPv6 loopback address.
if(IPAddress.IsLoopback(address)&& address.AddressFamily == AddressFamily.InterNetworkV6)
loopBack = " is an IPv6 loopback address " +
"whose internal format is: " + address.ToString() + ".";
else
if(IPAddress.IsLoopback(address) && address.AddressFamily == AddressFamily.InterNetwork)
loopBack = " is an IPv4 loopback address " +
"whose internal format is: " + address.ToString() + ".";

// Display the results.


Console.WriteLine("Your input address: " + "\"" + ipAddress + "\"" + loopBack);
}

catch(FormatException e)
{
Console.WriteLine("FormatException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

}
}

Remarks
The IsLoopback method compares address to Loopback and returns true if the two IP addresses are the same.
In the case of IPv4, that the IsLoopback method returns true for any IP address of the form 127.X.Y.Z (where X, Y, and
Z are in the range 0-255), not just Loopback (127.0.0.1).
IPAddress.Loopback IPAddress.Loopback
I n this Article
Provides the IP loopback address. This field is read-only.
public static readonly System.Net.IPAddress Loopback;
staticval mutable Loopback : System.Net.IPAddress

Returns
IPAddress IPAddress

Examples
The following example prints the Loopback address to the console.

public void PrintLoopbackAddress()


{
// Gets the IP loopback address and converts it to a string.
String IpAddressString = IPAddress.Loopback.ToString();
Console.WriteLine("Loopback IP address : " + IpAddressString);
}

Remarks
The Loopback field is equivalent to 127.0.0.1 in dotted-quad notation.
IPAddress.MapToIPv4 IPAddress.MapToIPv4
I n this Article
Maps the IPAddress object to an IPv4 address.
public System.Net.IPAddress MapToIPv4 ();
member this.MapToIPv4 : unit -> System.Net.IPAddress

Returns
IPAddress IPAddress
Returns IPAddress.
An IPv4 address.

Remarks
Dual-stack sockets always require IPv6 addresses. The ability to interact with an IPv4 address requires the use of the
IPv4-mapped IPv6 address format. Any IPv4 addresses must be represented in the IPv4-mapped IPv6 address format
which enables an IPv6 only application to communicate with an IPv4 node. The IPv4-mapped IPv6 address format
allows the IPv4 address of an IPv4 node to be represented as an IPv6 address. The IPv4 address is encoded into the
low -order 32 bits of the IPv6 address, and the high-order 96 bits hold the fixed prefix 0:0:0:0:0:FFFF. The IPv4-mapped
IPv6 address format is specified in RFC 4291. For more information, see www.ietf.org/rfc/rfc4291.txt.
If you want to use MapToIPv4 to convert an IPv4 address from IPv6 format to IPv4 format, you must first ensure that
you've got an IPv4 address. Call IsIPv4MappedToIPv6, which will return true if the IP address is originally IPv4
written as IPv6, or false otherwise. If IsIPv4MappedToIPv6 returns true , use MapToIPv4 to make the conversion.
IPAddress.MapToIPv6 IPAddress.MapToIPv6
I n this Article
Maps the IPAddress object to an IPv6 address.
public System.Net.IPAddress MapToIPv6 ();
member this.MapToIPv6 : unit -> System.Net.IPAddress

Returns
IPAddress IPAddress
Returns IPAddress.
An IPv6 address.

Remarks
Dual-stack sockets always require IPv6 addresses. The ability to interact with an IPv4 address requires the use of the
IPv4-mapped IPv6 address format. Any IPv4 addresses must be represented in the IPv4-mapped IPv6 address format
which enables an IPv6 only application to communicate with an IPv4 node. The IPv4-mapped IPv6 address format
allows the IPv4 address of an IPv4 node to be represented as an IPv6 address. The IPv4 address is encoded into the
low -order 32 bits of the IPv6 address, and the high-order 96 bits hold the fixed prefix 0:0:0:0:0:FFFF. The IPv4-mapped
IPv6 address format is specified in RFC 4291. For more information, see www.ietf.org/rfc/rfc4291.txt.
IPAddress.NetworkToHostOrder IPAddress.NetworkTo
HostOrder
I n this Article

Overloads
NetworkToHostOrder(Int32) NetworkToHostOrder(Int32)
Converts an integer value from network byte order to host
byte order.

NetworkToHostOrder(Int64) NetworkToHostOrder(Int64)
Converts a long value from network byte order to host byte
order.

NetworkToHostOrder(Int16) NetworkToHostOrder(Int16)
Converts a short value from network byte order to host byte
order.

NetworkToHostOrder(Int32) NetworkToHostOrder(Int32)
Converts an integer value from network byte order to host byte order.
public static int NetworkToHostOrder (int network);
static member NetworkToHostOrder : int -> int

Parameters
network Int32 Int32
The number to convert, expressed in network byte order.
Returns
Int32 Int32
An integer value, expressed in host byte order.
Examples
The following example uses the NetworkToHostOrder method to convert an integer value from network byte order to
host byte order.

public void NetworkToHostOrder_Integer(int networkByte)


{
int hostByte;
// Converts an integer value from network byte order to host byte order.
hostByte = IPAddress.NetworkToHostOrder(networkByte);
Console.WriteLine("Network byte order to Host byte order of {0} is {1}", networkByte, hostByte);
}

Remarks
Different computers use different conventions for ordering the bytes within multibyte integer values. Some computers
put the most significant byte first (known as big-endian order) and others put the least-significant byte first (known as
little-endian order). To work with computers that use different byte ordering, all integer values that are sent over the
network are sent in network byte order which has the most significant byte first.
The NetworkToHostOrder method converts multibyte integer values that are stored on the host system from the byte
order used by the network to the byte order used by the host.
See HostToNetworkOrder(Int64)HostToNetworkOrder(Int64)
Also

NetworkToHostOrder(Int64) NetworkToHostOrder(Int64)
Converts a long value from network byte order to host byte order.
public static long NetworkToHostOrder (long network);
static member NetworkToHostOrder : int64 -> int64

Parameters
network Int64 Int64
The number to convert, expressed in network byte order.
Returns
Int64 Int64
A long value, expressed in host byte order.
Examples
The following example uses the NetworkToHostOrder method to convert a long value from network byte order to host
byte order.
public void NetworkToHostOrder_Long(long networkByte)
{
long hostByte;
// Converts a long value from network byte order to host byte order.
hostByte = IPAddress.NetworkToHostOrder(networkByte);
Console.WriteLine("Network byte order to Host byte order of {0} is {1}", networkByte, hostByte);
}

Remarks
Different computers use different conventions for ordering the bytes within multibyte integer values. Some computers
put the most significant byte first (known as big-endian order) and others put the least-significant byte first (known as
little-endian order). To work with computers that use different byte ordering, all integer values that are sent over the
network are sent in network byte order which has the most significant byte first.
The NetworkToHostOrder method converts multibyte integer values that are stored on the host system from the byte
order used by the network to the byte order used by the host.
See HostToNetworkOrder(Int64)HostToNetworkOrder(Int64)
Also

NetworkToHostOrder(Int16) NetworkToHostOrder(Int16)
Converts a short value from network byte order to host byte order.

public static short NetworkToHostOrder (short network);


static member NetworkToHostOrder : int16 -> int16
Parameters
network Int16 Int16
The number to convert, expressed in network byte order.
Returns
Int16 Int16
A short value, expressed in host byte order.
Examples
The following example uses the NetworkToHostOrder method to convert a short value from network byte order to
host byte order.

public void NetworkToHostOrder_Short(short networkByte)


{
short hostByte;
// Converts a short value from network byte order to host byte order.
hostByte = IPAddress.NetworkToHostOrder(networkByte);
Console.WriteLine("Network byte order to Host byte order of {0} is {1}", networkByte, hostByte);
}

Remarks
Different computers use different conventions for ordering the bytes within multibyte integer values. Some computers
put the most significant byte first (known as big-endian order) and others put the least-significant byte first (known as
little-endian order). To work with computers that use different byte ordering, all integer values that are sent over the
network are sent in network byte order which has the most significant byte first.
The NetworkToHostOrder method converts multibyte integer values that are stored on the host system from the byte
order used by the network to the byte order used by the host.
See HostToNetworkOrder(Int64)HostToNetworkOrder(Int64)
Also
IPAddress.None IPAddress.None
I n this Article
Provides an IP address that indicates that no network interface should be used. This field is read-only.
public static readonly System.Net.IPAddress None;
staticval mutable None : System.Net.IPAddress

Returns
IPAddress IPAddress

Examples
The following example uses the None property to indicate that no network interface should be used.

public static void Main()


{
// Gets the IP address indicating that no network interface should be used
// and converts it to a string.
string address = IPAddress.None.ToString();
Console.WriteLine("IP address : " + address);
}

Remarks
The Socket.Bind method uses the None field to indicate that a Socket must not listen for client activity. The None field
is equivalent to 255.255.255.255 in dotted-quad notation.
IPAddress.Parse IPAddress.Parse
I n this Article

Overloads
Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>)

Parse(String) Parse(String)
Converts an IP address string to an IPAddress instance.

Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>)
public static System.Net.IPAddress Parse (ReadOnlySpan<char> ipString);
static member Parse : ReadOnlySpan<char> -> System.Net.IPAddress

Parameters
ipString ReadOnlySpan<Char>
Returns
IPAddress IPAddress

Parse(String) Parse(String)
Converts an IP address string to an IPAddress instance.

public static System.Net.IPAddress Parse (string ipString);


static member Parse : string -> System.Net.IPAddress

Parameters
ipString String String
A string that contains an IP address in dotted-quad notation for IPv4 and in colon-hexadecimal notation for IPv6.
Returns
IPAddress IPAddress
An IPAddress instance.
Exceptions
ArgumentNullException ArgumentNullException
ipString is null .
FormatException FormatException
ipString is not a valid IP address.
Examples
The following code converts a string that contains an IP address, in dotted-quad notation for IPv4 or in colon-
hexadecimal notation for IPv6, into an instance of the IPAddress class. Then it uses the overloaded ToString method to
display the address in standard notation.
using System;
using System.Net;

class ParseAddress
{

private static void Main(string[] args)


{
string IPaddress;

if (args.Length == 0)
{
Console.WriteLine("Please enter an IP address.");
Console.WriteLine("Usage: >cs_parse any IPv4 or IPv6 address.");
Console.WriteLine("Example: >cs_parse 127.0.0.1");
Console.WriteLine("Example: >cs_parse 0:0:0:0:0:0:0:1");
return;
}
else
IPaddress = args[0];

// Get the list of the IPv6 addresses associated with the requested host.
Parse(IPaddress);

// This method calls the IPAddress.Parse method to check the ipAddress


// input string. If the ipAddress argument represents a syntatically correct IPv4 or
// IPv6 address, the method displays the Parse output into quad-notation or
// colon-hexadecimal notation, respectively. Otherwise, it displays an
// error message.
private static void Parse(string ipAddress)
{
try
{
// Create an instance of IPAddress for the specified address string (in
// dotted-quad, or colon-hexadecimal notation).
IPAddress address = IPAddress.Parse(ipAddress);

// Display the address in standard notation.


Console.WriteLine("Parsing your input string: " + "\"" + ipAddress + "\"" + " produces this
address (shown in its standard notation): "+ address.ToString());
}

catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

catch(FormatException e)
{
Console.WriteLine("FormatException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}

catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
}

Remarks
The static Parse method creates an IPAddress instance from an IP address expressed in dotted-quad notation for IPv4
and in colon-hexadecimal notation for IPv6.
The number of parts (each part is separated by a period) in ipString determines how the IP address is constructed. A
one part address is stored directly in the network address. A two part address, convenient for specifying a class A
address, puts the leading part in the first byte and the trailing part in the right-most three bytes of the network address.
A three part address, convenient for specifying a class B address, puts the first part in the first byte, the second part in
the second byte, and the final part in the right-most two bytes of the network address. For example:

NU MB ER O F PAR TS AND E X AMPLE IPSTRING IPV4 AD D R ES S FO R IPAD D R ES S

1 -- "65535" 0.0.255.255

2 -- "20.2" 20.0.0.2

2 -- "20.65535" 20.0.255.255

3 -- "128.1.2" 128.1.0.2
IPAddress.ScopeId IPAddress.ScopeId
I n this Article
Gets or sets the IPv6 address scope identifier.
public long ScopeId { get; set; }
member this.ScopeId : int64 with get, set

Returns
Int64 Int64
A long integer that specifies the scope of the address.
Exceptions
SocketException SocketException
AddressFamily = InterNetwork .
ArgumentOutOfRangeException ArgumentOutOfRangeException
scopeId <0
-or-
scopeId > 0x00000000FFFFFFFF

Examples
// Display the type of address family supported by the server. If the
// server is IPv6-enabled this value is: InterNetworkV6. If the server
// is also IPv4-enabled there will be an additional value of InterNetwork.
Console.WriteLine("AddressFamily: " + curAdd.AddressFamily.ToString());

// Display the ScopeId property in case of IPV6 addresses.


if(curAdd.AddressFamily.ToString() == ProtocolFamily.InterNetworkV6.ToString())
Console.WriteLine("Scope Id: " + curAdd.ScopeId.ToString());

Remarks
The meaning of ScopeId changes depending on the context in which it is used.
Link-local address. On a host with multiple interfaces connected to separate links, the same link-local address can be
assigned to multiple interfaces. To eliminate this ambiguity, a scope identifier is used to specify the interface over which
messages are exchanged.
Note

Link-local addresses, identified by the Format Prefix (FP ) FE80, are used by nodes when communicating with
neighboring nodes on the same link.
Site-local addresses. A host can be connected to multiple sites. In this case, a scope identifier is used to indicate a
specific site to communicate with.
Note

Site-local addresses, identified by the Format Prefix (FP ) FEC0, are used by nodes when communicating on private
intranets.
The notation that is used to specify the ScopeId with an address is Address%ScopeId . For example,
FE80::5EFE:192.168.41.30%2.
IPAddress.ToString IPAddress.ToString
I n this Article
Converts an Internet address to its standard notation.
public override string ToString ();
override this.ToString : unit -> string

Returns
String String
A string that contains the IP address in either IPv4 dotted-quad or in IPv6 colon-hexadecimal notation.
Exceptions
SocketException SocketException
The address family is InterNetworkV6 and the address is bad.

Remarks
The ToString method converts the IP address that is stored in the Address property to either IPv4 dotted-quad or IPv6
colon-hexadecimal notation.
IPAddress.TryFormat IPAddress.TryFormat
I n this Article
public bool TryFormat (Span<char> destination, out int charsWritten);
member this.TryFormat : Span<char> * -> bool

Parameters
destination Span<Char>
charsWritten Int32 Int32
Returns
Boolean Boolean
IPAddress.TryParse IPAddress.TryParse
I n this Article

Overloads
TryParse(String, IPAddress) TryParse(String, IPAddress)
Determines whether a string is a valid IP address.

TryParse(ReadOnlySpan<Char>, IPAddress) TryParse(ReadOnlySpan<Char>, IPAddress)

TryParse(String, IPAddress) TryParse(String, IPAddress)


Determines whether a string is a valid IP address.
public static bool TryParse (string ipString, out System.Net.IPAddress address);
static member TryParse : string * -> bool

Parameters
ipString String String
The string to validate.
address IPAddress IPAddress
The IPAddress version of the string.
Returns
Boolean Boolean
true if ipString was able to be parsed as an IP address; otherwise, false .
Exceptions
ArgumentNullException ArgumentNullException
ipString is null.
Remarks
Note that this method accepts as valid an ipString value that can be parsed as an Int64, and then treats that Int64 as
the long value of an IP address in network byte order, similar to the way that the IPAddress constructor does. This
means that this method returns true if the Int64 is parsed successfully, even if it represents an address that's not a valid
IP address. For example, if ipString is "1", this method returns true even though "1" (or 0.0.0.1) is not a valid IP address
and you might expect this method to return false. Fixing this bug would break existing apps, so the current behavior
will not be changed. Your code can avoid this behavior by ensuring that it only uses this method to parse IP addresses
in dotted-decimal format.

TryParse(ReadOnlySpan<Char>, IPAddress)
TryParse(ReadOnlySpan<Char>, IPAddress)
public static bool TryParse (ReadOnlySpan<char> ipString, out System.Net.IPAddress address);
static member TryParse : ReadOnlySpan<char> * -> bool
Parameters
ipString ReadOnlySpan<Char>
address IPAddress IPAddress
Returns
Boolean Boolean
IPAddress.TryWriteBytes IPAddress.TryWriteBytes
I n this Article
public bool TryWriteBytes (Span<byte> destination, out int bytesWritten);
member this.TryWriteBytes : Span<byte> * -> bool

Parameters
destination Span<Byte>
bytesWritten Int32 Int32
Returns
Boolean Boolean
IPEndPoint IPEndPoint Class
Represents a network endpoint as an IP address and a port number.

D eclaration
[System.Serializable]
public class IPEndPoint : System.Net.EndPoint
type IPEndPoint = class
inherit EndPoint

I nheritance H ierarchy
Object Object
EndPoint EndPoint

Remarks
The IPEndPoint class contains the host and local or remote port information needed by an application to connect to a
service on a host. By combining the host's IP address and port number of a service, the IPEndPoint class forms a
connection point to a service.

Constructors
IPEndPoint(Int64, Int32)
IPEndPoint(Int64, Int32)

Initializes a new instance of the IPEndPoint class with the specified address and port number.

IPEndPoint(IPAddress, Int32)
IPEndPoint(IPAddress, Int32)

Initializes a new instance of the IPEndPoint class with the specified address and port number.

Fields
MaxPort
MaxPort

Specifies the maximum value that can be assigned to the Port property. The MaxPort value is set to 0x0000FFFF.
This field is read-only.

MinPort
MinPort

Specifies the minimum value that can be assigned to the Port property. This field is read-only.

Properties
Address
Address

Gets or sets the IP address of the endpoint.

AddressFamily
AddressFamily

Gets the Internet Protocol (IP ) address family.

Port
Port

Gets or sets the port number of the endpoint.

Methods
Create(SocketAddress)
Create(SocketAddress)

Creates an endpoint from a socket address.

Equals(Object)
Equals(Object)

Determines whether the specified Object is equal to the current Object.

GetHashCode()
GetHashCode()

Returns a hash value for a IPEndPoint instance.

Parse(ReadOnlySpan<Char>)
Parse(ReadOnlySpan<Char>)

Parse(String)
Parse(String)

Serialize()
Serialize()

Serializes endpoint information into a SocketAddress instance.


ToString()
ToString()

Returns the IP address and port number of the specified endpoint.

TryParse(ReadOnlySpan<Char>, IPEndPoint)
TryParse(ReadOnlySpan<Char>, IPEndPoint)

TryParse(String, IPEndPoint)
TryParse(String, IPEndPoint)
IPEndPoint.Address IPEndPoint.Address
I n this Article
Gets or sets the IP address of the endpoint.
public System.Net.IPAddress Address { get; set; }
member this.Address : System.Net.IPAddress with get, set

Returns
IPAddress IPAddress
An IPAddress instance containing the IP address of the endpoint.

Examples
The following example sets the Address property using the IPAddress specified.
private static void displayEndpointInfo(IPEndPoint endpoint)
{
Console.WriteLine("Endpoint.Address : " + endpoint.Address);
Console.WriteLine("Endpoint.AddressFamily : " + endpoint.AddressFamily);
Console.WriteLine("Endpoint.Port : " + endpoint.Port);
Console.WriteLine("Endpoint.ToString() : " + endpoint.ToString());

Console.WriteLine("Press any key to continue.");


Console.ReadLine();
}
IPEndPoint.AddressFamily IPEndPoint.AddressFamily
I n this Article
Gets the Internet Protocol (IP ) address family.
public override System.Net.Sockets.AddressFamily AddressFamily { get; }
member this.AddressFamily : System.Net.Sockets.AddressFamily

Returns
AddressFamily AddressFamily
Returns InterNetwork.

Examples
The following example uses the AddressFamily property to return the AddressFamily to which the IPEndPoint belongs.
In this case it is the InterNetworkAddressFamily.
private static void displayEndpointInfo(IPEndPoint endpoint)
{
Console.WriteLine("Endpoint.Address : " + endpoint.Address);
Console.WriteLine("Endpoint.AddressFamily : " + endpoint.AddressFamily);
Console.WriteLine("Endpoint.Port : " + endpoint.Port);
Console.WriteLine("Endpoint.ToString() : " + endpoint.ToString());

Console.WriteLine("Press any key to continue.");


Console.ReadLine();
}

See EndPointEndPoint
Also
IPEndPoint.Create IPEndPoint.Create
I n this Article
Creates an endpoint from a socket address.
public override System.Net.EndPoint Create (System.Net.SocketAddress socketAddress);
override this.Create : System.Net.SocketAddress -> System.Net.EndPoint

Parameters
socketAddress SocketAddress SocketAddress
The SocketAddress to use for the endpoint.
Returns
EndPoint EndPoint
An EndPoint instance using the specified socket address.
Exceptions
ArgumentException ArgumentException
The AddressFamily of socketAddress is not equal to the AddressFamily of the current instance.
-or-
socketAddress .Size < 8.

Examples
The following example uses the specified SocketAddress to create an IPEndPoint.
// Recreate the connection endpoint from the serialized information.
IPEndPoint endpoint = new IPEndPoint(0,0);
IPEndPoint clonedIPEndPoint = (IPEndPoint) endpoint.Create(socketAddress);
Console.WriteLine("clonedIPEndPoint: " + clonedIPEndPoint.ToString());

See EndPointEndPoint
Also SocketAddressSocketAddress
IPEndPoint.Equals IPEndPoint.Equals
I n this Article
Determines whether the specified Object is equal to the current Object.
public override bool Equals (object comparand);
override this.Equals : obj -> bool

Parameters
comparand Object Object
The Object to compare with the current Object.
Returns
Boolean Boolean
true if the specified Object is equal to the current Object; otherwise, false .
IPEndPoint.GetHashCode IPEndPoint.GetHashCode
I n this Article
Returns a hash value for a IPEndPoint instance.
public override int GetHashCode ();
override this.GetHashCode : unit -> int

Returns
Int32 Int32
An integer hash value.

Remarks
The GetHashCode method returns a hash code of the IP endpoint instance. This value can be used as a key in hash
tables.
IPEndPoint IPEndPoint
I n this Article

Overloads
IPEndPoint(Int64, Int32) IPEndPoint(Int64, Int32)
Initializes a new instance of the IPEndPoint class with the
specified address and port number.

IPEndPoint(IPAddress, Int32) IPEndPoint(IPAddress, Int32)


Initializes a new instance of the IPEndPoint class with the
specified address and port number.

IPEndPoint(Int64, Int32) IPEndPoint(Int64, Int32)


Initializes a new instance of the IPEndPoint class with the specified address and port number.
public IPEndPoint (long address, int port);
new System.Net.IPEndPoint : int64 * int -> System.Net.IPEndPoint

Parameters
address Int64 Int64
The IP address of the Internet host.
port Int32 Int32
The port number associated with the address , or 0 to specify any available port. port is in host order.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
port is less than MinPort.
-or-
port is greater than MaxPort.
-or-
address is less than 0 or greater than 0x00000000FFFFFFFF.
Examples
The following example uses the specified IP address and port number to create an IPEndPoint.
IPAddress hostIPAddress1 = (Dns.Resolve(hostString1)).AddressList[0];
Console.WriteLine(hostIPAddress1.ToString());
IPEndPoint hostIPEndPoint = new IPEndPoint(hostIPAddress1,80);
Console.WriteLine("
IPEndPoint information:" + hostIPEndPoint.ToString());
Console.WriteLine("
Maximum allowed Port Address :" + IPEndPoint.MaxPort);
Console.WriteLine("
Minimum allowed Port Address :" + IPEndPoint.MinPort);
Console.WriteLine("
Address Family :" + hostIPEndPoint.AddressFamily);

IPEndPoint(IPAddress, Int32) IPEndPoint(IPAddress, Int32)


Initializes a new instance of the IPEndPoint class with the specified address and port number.
public IPEndPoint (System.Net.IPAddress address, int port);
new System.Net.IPEndPoint : System.Net.IPAddress * int -> System.Net.IPEndPoint

Parameters
address IPAddress IPAddress
An IPAddress.
port Int32 Int32
The port number associated with the address , or 0 to specify any available port. port is in host order.

Exceptions
ArgumentNullException ArgumentNullException
address is null .
ArgumentOutOfRangeException ArgumentOutOfRangeException
port is less than MinPort.
-or-
port is greater than MaxPort.
-or-
address is less than 0 or greater than 0x00000000FFFFFFFF.
Examples
// Obtain the IP address from the list of IP addresses associated with the server.
foreach(IPAddress address in host.AddressList)
{
IPEndPoint endpoint = new IPEndPoint(address, port);

tempSocket =
new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

tempSocket.Connect(endpoint);

if(tempSocket.Connected)
{
// Display the endpoint information.
displayEndpointInfo(endpoint);
// Serialize the endpoint to obtain a SocketAddress object.
serializedSocketAddress = serializeEndpoint(endpoint);
break;
}
else
continue;
}
IPEndPoint.MaxPort IPEndPoint.MaxPort
I n this Article
Specifies the maximum value that can be assigned to the Port property. The MaxPort value is set to 0x0000FFFF. This
field is read-only.

public const int MaxPort = 65535;


val mutable MaxPort : int

Returns
Int32 Int32

Examples
The following example uses the MaxPort property to print the maximum value that can be assigned to the Port
property.

IPAddress hostIPAddress1 = (Dns.Resolve(hostString1)).AddressList[0];


Console.WriteLine(hostIPAddress1.ToString());
IPEndPoint hostIPEndPoint = new IPEndPoint(hostIPAddress1,80);
Console.WriteLine("\nIPEndPoint information:" + hostIPEndPoint.ToString());
Console.WriteLine("\n\tMaximum allowed Port Address :" + IPEndPoint.MaxPort);
Console.WriteLine("\n\tMinimum allowed Port Address :" + IPEndPoint.MinPort);
Console.WriteLine("\n\tAddress Family :" + hostIPEndPoint.AddressFamily);
IPEndPoint.MinPort IPEndPoint.MinPort
I n this Article
Specifies the minimum value that can be assigned to the Port property. This field is read-only.
public const int MinPort = 0;
val mutable MinPort : int

Returns
Int32 Int32

Examples
The following example uses the MinPort property to print the minimum value that can be assigned to the Port
property.

IPAddress hostIPAddress1 = (Dns.Resolve(hostString1)).AddressList[0];


Console.WriteLine(hostIPAddress1.ToString());
IPEndPoint hostIPEndPoint = new IPEndPoint(hostIPAddress1,80);
Console.WriteLine("\nIPEndPoint information:" + hostIPEndPoint.ToString());
Console.WriteLine("\n\tMaximum allowed Port Address :" + IPEndPoint.MaxPort);
Console.WriteLine("\n\tMinimum allowed Port Address :" + IPEndPoint.MinPort);
Console.WriteLine("\n\tAddress Family :" + hostIPEndPoint.AddressFamily);
IPEndPoint.Parse IPEndPoint.Parse
I n this Article

Overloads
Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>)

Parse(String) Parse(String)

Parse(ReadOnlySpan<Char>) Parse(ReadOnlySpan<Char>)
public static System.Net.IPEndPoint Parse (ReadOnlySpan<char> s);
static member Parse : ReadOnlySpan<char> -> System.Net.IPEndPoint

Parameters
s ReadOnlySpan<Char>
Returns
IPEndPoint IPEndPoint

Parse(String) Parse(String)
public static System.Net.IPEndPoint Parse (string s);
static member Parse : string -> System.Net.IPEndPoint

Parameters
s String String
Returns
IPEndPoint IPEndPoint
IPEndPoint.Port IPEndPoint.Port
I n this Article
Gets or sets the port number of the endpoint.
public int Port { get; set; }
member this.Port : int with get, set

Returns
Int32 Int32
An integer value in the range MinPort to MaxPort indicating the port number of the endpoint.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value that was specified for a set operation is less than MinPort or greater than MaxPort.

Examples
The following example uses the Port property to set TCP port number of the EndPoint.
private static void displayEndpointInfo(IPEndPoint endpoint)
{
Console.WriteLine("Endpoint.Address : " + endpoint.Address);
Console.WriteLine("Endpoint.AddressFamily : " + endpoint.AddressFamily);
Console.WriteLine("Endpoint.Port : " + endpoint.Port);
Console.WriteLine("Endpoint.ToString() : " + endpoint.ToString());

Console.WriteLine("Press any key to continue.");


Console.ReadLine();
}
IPEndPoint.Serialize IPEndPoint.Serialize
I n this Article
Serializes endpoint information into a SocketAddress instance.
public override System.Net.SocketAddress Serialize ();
override this.Serialize : unit -> System.Net.SocketAddress

Returns
SocketAddress SocketAddress
A SocketAddress instance containing the socket address for the endpoint.

Examples
The following example uses the Serialize method to serialize endpoint information into a SocketAddress instance.
// The serializeEndpoint method serializes the endpoint and returns the
// SocketAddress containing the serialized endpoint data.
private static SocketAddress serializeEndpoint(IPEndPoint endpoint)
{

// Serialize IPEndPoint details to a SocketAddress instance.


SocketAddress socketAddress = endpoint.Serialize();

// Display the serialized endpoint information.


Console.WriteLine("Endpoint.Serialize() : " + socketAddress.ToString());

Console.WriteLine("Socket.Family : " + socketAddress.Family);


Console.WriteLine("Socket.Size : " + socketAddress.Size);

Console.WriteLine("Press any key to continue.");


Console.ReadLine();

return socketAddress;
}

See EndPointEndPoint
Also
IPEndPoint.ToString IPEndPoint.ToString
I n this Article
Returns the IP address and port number of the specified endpoint.
public override string ToString ();
override this.ToString : unit -> string

Returns
String String
A string containing the IP address and the port number of the specified endpoint (for example, 192.168.1.2:80).

Examples
The following example returns a string representation of the IP address and port number of the specified IPEndPoint.
private static void displayEndpointInfo(IPEndPoint endpoint)
{
Console.WriteLine("Endpoint.Address : " + endpoint.Address);
Console.WriteLine("Endpoint.AddressFamily : " + endpoint.AddressFamily);
Console.WriteLine("Endpoint.Port : " + endpoint.Port);
Console.WriteLine("Endpoint.ToString() : " + endpoint.ToString());

Console.WriteLine("Press any key to continue.");


Console.ReadLine();
}
IPEndPoint.TryParse IPEndPoint.TryParse
I n this Article

Overloads
TryParse(ReadOnlySpan<Char>, IPEndPoint) TryParse(ReadOnlySpan<Char>, IPEndPoint)

TryParse(String, IPEndPoint) TryParse(String, IPEndPoint)

TryParse(ReadOnlySpan<Char>, IPEndPoint)
TryParse(ReadOnlySpan<Char>, IPEndPoint)
public static bool TryParse (ReadOnlySpan<char> s, out System.Net.IPEndPoint result);
static member TryParse : ReadOnlySpan<char> * -> bool

Parameters
s ReadOnlySpan<Char>
result IPEndPoint IPEndPoint
Returns
Boolean Boolean

TryParse(String, IPEndPoint) TryParse(String, IPEndPoint)


public static bool TryParse (string s, out System.Net.IPEndPoint result);
static member TryParse : string * -> bool

Parameters
s String String
result IPEndPoint IPEndPoint
Returns
Boolean Boolean
IPEndPointCollection IPEndPointCollection Class
Represents a collection used to store network endpoints as IPEndPoint objects.

D eclaration
[System.Serializable]
public class IPEndPointCollection :
System.Collections.ObjectModel.Collection<System.Net.IPEndPoint>
type IPEndPointCollection = class
inherit Collection<IPEndPoint>

I nheritance H ierarchy
Object Object
Collection<T> Collection<T>

Remarks
The IPEndPointCollection class is derived from the System.Collections.ObjectModel.Collection<T> class.
The IPEndPoint class contains the host and local or remote port information needed by an application to connect to a
service on a host. By combining the host's IP address and port number of a service, the IPEndPoint class forms a
connection point to a service.
The IPEndPointCollection class is used by classes in the System.Net.PeerToPeer namespace.

Constructors
IPEndPointCollection()
IPEndPointCollection()

Initializes a new instance of the IPEndPointCollection class.

Methods
InsertItem(Int32, IPEndPoint)
InsertItem(Int32, IPEndPoint)

Inserts an IPEndPoint element into the IPEndPointCollection at the specified index.

SetItem(Int32, IPEndPoint)
SetItem(Int32, IPEndPoint)

Replaces the IPEndPoint element at the specified index.

Thread Safety
Public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed
to be thread safe.
A IPEndPointCollection can support multiple readers concurrently, as long as the collection is not modified. Even so,
enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during
enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by
multiple threads for reading and writing, you must implement your own synchronization.
IPEndPointCollection.InsertItem IPEndPointCollection.
InsertItem
I n this Article
Inserts an IPEndPoint element into the IPEndPointCollection at the specified index.

protected override void InsertItem (int index, System.Net.IPEndPoint item);


override this.InsertItem : int * System.Net.IPEndPoint -> unit

Parameters
index Int32 Int32
The zero-based index at which item should be inserted.
item IPEndPoint IPEndPoint
The IPEndPoint object to insert. The value can be null for reference types.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The index parameter is less than zero
-or-
the index parameter is greater than the current count of items in the IPEndPointCollection.
ArgumentNullException ArgumentNullException
The item parameter is null .

Remarks
IPEndPointCollection does not accept null as a valid value. IPEndPointCollection allows duplicate elements.
If index is equal to current count of items in the IPEndPointCollection , then the item is added to the end of
IPEndPointCollection.
This method is an O ( n ) operation, where n is Collection<T>.Count.
IPEndPointCollection
I n this Article
Initializes a new instance of the IPEndPointCollection class.
public IPEndPointCollection ();
IPEndPointCollection.SetItem IPEndPointCollection.Set
Item
I n this Article
Replaces the IPEndPoint element at the specified index.

protected override void SetItem (int index, System.Net.IPEndPoint item);


override this.SetItem : int * System.Net.IPEndPoint -> unit

Parameters
index Int32 Int32
The zero-based index of the element to replace.
item IPEndPoint IPEndPoint
The new IPEndPoint value for the element at the specified index. The value can be null for reference types.

Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The index parameter is less than zero
-or-
the index parameter is greater than the current count of items in the IPEndPointCollection.
ArgumentNullException ArgumentNullException
The item parameter is null .

Remarks
IPEndPointCollection does not accept null as a valid value. IPEndPointCollection allows duplicate elements.
This method is an O (1) operation.
IPHostEntry IPHostEntry Class
Provides a container class for Internet host address information.

D eclaration
public class IPHostEntry
type IPHostEntry = class

I nheritance H ierarchy
Object Object

Remarks
The IPHostEntry class associates a Domain Name System (DNS ) host name with an array of aliases and an array of
matching IP addresses.
The IPHostEntry class is used as a helper class with the Dns class.

Constructors
IPHostEntry()
IPHostEntry()

Initializes a new instance of the IPHostEntry class.

Properties
AddressList
AddressList

Gets or sets a list of IP addresses that are associated with a host.

Aliases
Aliases

Gets or sets a list of aliases that are associated with a host.

HostName
HostName

Gets or sets the DNS name of the host.


IPHostEntry.AddressList IPHostEntry.AddressList
I n this Article
Gets or sets a list of IP addresses that are associated with a host.
public System.Net.IPAddress[] AddressList { get; set; }
member this.AddressList : System.Net.IPAddress[] with get, set

Returns
IPAddress[]
An array of type IPAddress that contains IP addresses that resolve to the host names that are contained in the Aliases
property.

Examples
The following example uses the AddressList property to access the IP addresses that are associated with the
IPHostEntry.

public void GetIpAddressList(String hostString)


{
try
{
// Get 'IPHostEntry' object containing information like host name, IP addresses, aliases for a
host.
IPHostEntry hostInfo = Dns.GetHostByName(hostString);
Console.WriteLine("Host name : " + hostInfo.HostName);
Console.WriteLine("IP address List : ");
for(int index=0; index < hostInfo.AddressList.Length; index++)
{
Console.WriteLine(hostInfo.AddressList[index]);
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
IPHostEntry.Aliases IPHostEntry.Aliases
I n this Article
Gets or sets a list of aliases that are associated with a host.
public string[] Aliases { get; set; }
member this.Aliases : string[] with get, set

Returns
String[]
An array of strings that contain DNS names that resolve to the IP addresses in the AddressList property.
IPHostEntry.HostName IPHostEntry.HostName
I n this Article
Gets or sets the DNS name of the host.
public string HostName { get; set; }
member this.HostName : string with get, set

Returns
String String
A string that contains the primary host name for the server.

Examples
The following example uses the HostName property to retrieve the primary host name.

public void GetIpAddressList(String hostString)


{
try
{
// Get 'IPHostEntry' object containing information like host name, IP addresses, aliases for a
host.
IPHostEntry hostInfo = Dns.GetHostByName(hostString);
Console.WriteLine("Host name : " + hostInfo.HostName);
Console.WriteLine("IP address List : ");
for(int index=0; index < hostInfo.AddressList.Length; index++)
{
Console.WriteLine(hostInfo.AddressList[index]);
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
catch(Exception e)
{
Console.WriteLine("Exception caught!!!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}

Remarks
The HostName property contains the primary host name for a server. If the DNS entry for the server defines
additional aliases, they will be available in the Aliases property.
IPHostEntry
I n this Article
Initializes a new instance of the IPHostEntry class.
public IPHostEntry ();
IUnsafeWebRequestCreate IUnsafeWebRequestCreate
Interface
Creates an unsafe WebRequest to a Uniform Resource Identifier (URI).

D eclaration
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be
used directly from your code.", true)]
public interface IUnsafeWebRequestCreate
type IUnsafeWebRequestCreate = interface

I nheritance H ierarchy
None

Methods
Create(Uri)
Create(Uri)

Initializes a new WebRequest for the specified URI scheme.


IUnsafeWebRequestCreate.Create IUnsafeWebRequest
Create.Create
I n this Article
Initializes a new WebRequest for the specified URI scheme.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public System.Net.WebRequest Create (Uri uri);
abstract member Create : Uri -> System.Net.WebRequest

Parameters
uri Uri Uri
The URI of the requested resource.
Returns
WebRequest WebRequest
Returns WebRequest.
A WebRequest descendant for the specified URI scheme.
Attributes ObsoleteAttribute
IWebProxy IWebProxy Interface
Provides the base interface for implementation of proxy access for the WebRequest class.

D eclaration
public interface IWebProxy
type IWebProxy = interface

I nheritance H ierarchy
None

Remarks
The IWebProxy interface provides the methods and properties that are required by the WebRequest class to access
proxy servers.
The WebProxy class is the base implementation of the IWebProxy interface.

Properties
Credentials
Credentials

The credentials to submit to the proxy server for authentication.

Methods
GetProxy(Uri)
GetProxy(Uri)

Returns the URI of a proxy.

IsBypassed(Uri)
IsBypassed(Uri)

Indicates that the proxy should not be used for the specified host.
IWebProxy.Credentials IWebProxy.Credentials
I n this Article
The credentials to submit to the proxy server for authentication.
public System.Net.ICredentials Credentials { get; set; }
member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials instance that contains the credentials that are needed to authenticate a request to the proxy server.

Examples
The following example uses the Credentials property to set the credentials that will be submitted to the proxy server
for authentication.
public class WebProxy_Interface : IWebProxy

// The credentials to be used with the web proxy.


private ICredentials iCredentials;

// Uri of the associated proxy server.


private Uri webProxyUri;

public WebProxy_Interface(Uri proxyUri) {

webProxyUri = proxyUri;

// Get and Set the Credentials property.


public ICredentials Credentials {
get {
return iCredentials;
}
set {
if(iCredentials != value)
iCredentials = value;
}
}

// Return the web proxy for the specified destination(destUri).


public Uri GetProxy(Uri destUri) {

// Always use the same proxy.


return webProxyUri;

// Return whether the web proxy should be bypassed for the specified destination(hostUri).
public bool IsBypassed(Uri hostUri) {

// Never bypass the proxy.


return false;

}
};

Remarks
The Credentials property is an ICredentials instance that contains the authorization credentials to send to the proxy
server in response to an HTTP 407 (proxy authorization) status code.
IWebProxy.GetProxy IWebProxy.GetProxy
I n this Article
Returns the URI of a proxy.
public Uri GetProxy (Uri destination);
abstract member GetProxy : Uri -> Uri

Parameters
destination Uri Uri
A Uri that specifies the requested Internet resource.
Returns
Uri Uri
A Uri instance that contains the URI of the proxy used to contact destination .

Examples
The following example uses the GetProxy method to return the URI that the WebRequest uses to access the Internet
resource.
WebProxy_Interface webProxy_Interface = new WebProxy_Interface(new Uri("http://proxy.example.com"));

webProxy_Interface.Credentials = new NetworkCredential("myusername", "mypassword");

Console.WriteLine("The web proxy is : {0}", webProxy_Interface.GetProxy(new


Uri("http://www.contoso.com")));

// Determine whether the Web proxy can be bypassed for the site "http://www.contoso.com".
if(webProxy_Interface.IsBypassed(new Uri("http://www.contoso.com")))
Console.WriteLine("Web Proxy is by passed");
else
Console.WriteLine("Web Proxy is not by passed");

Remarks
The GetProxy method returns the URI of the proxy server that handles requests to the Internet resource that is
specified in the destination parameter.
IWebProxy.IsBypassed IWebProxy.IsBypassed
I n this Article
Indicates that the proxy should not be used for the specified host.
public bool IsBypassed (Uri host);
abstract member IsBypassed : Uri -> bool

Parameters
host Uri Uri
The Uri of the host to check for proxy use.
Returns
Boolean Boolean
true if the proxy server should not be used for host ; otherwise, false .

Examples
The following example uses the IsBypassed property to determine whether the proxy server should be used for the
specified host.
WebProxy_Interface webProxy_Interface = new WebProxy_Interface(new Uri("http://proxy.example.com"));

webProxy_Interface.Credentials = new NetworkCredential("myusername", "mypassword");

Console.WriteLine("The web proxy is : {0}", webProxy_Interface.GetProxy(new


Uri("http://www.contoso.com")));

// Determine whether the Web proxy can be bypassed for the site "http://www.contoso.com".
if(webProxy_Interface.IsBypassed(new Uri("http://www.contoso.com")))
Console.WriteLine("Web Proxy is by passed");
else
Console.WriteLine("Web Proxy is not by passed");

Remarks
The IsBypassed method indicates whether to use the proxy server to access the host that is specified in the host
parameter. If IsBypassed is true , the proxy is not used to contact the host and the request is passed directly to the
server.
IWebProxyScript IWebProxyScript Interface
Provides the base interface to load and execute scripts for automatic proxy detection.

D eclaration
public interface IWebProxyScript
type IWebProxyScript = interface

I nheritance H ierarchy
None

Methods
Close()
Close()

Closes a script.

Load(Uri, String, Type)


Load(Uri, String, Type)

Loads a script.

Run(String, String)
Run(String, String)

Runs a script.
IWebProxyScript.Close IWebProxyScript.Close
I n this Article
Closes a script.
public void Close ();
abstract member Close : unit -> unit
IWebProxyScript.Load IWebProxyScript.Load
I n this Article
Loads a script.
public bool Load (Uri scriptLocation, string script, Type helperType);
abstract member Load : Uri * string * Type -> bool

Parameters
scriptLocation Uri Uri
Internal only.
script String String
Internal only.
helperType Type Type
Internal only.
Returns
Boolean Boolean
A Boolean indicating whether the script was successfully loaded.
IWebProxyScript.Run IWebProxyScript.Run
I n this Article
Runs a script.
public string Run (string url, string host);
abstract member Run : string * string -> string

Parameters
url String String
Internal only.
host String String
Internal only.
Returns
String String
A String.
An internal-only value returned.

Remarks
When the HttpWebRequest object is run, it may need to run the WPAD (Web Proxy Automatic Detection) protocol to
detect whether a proxy is required for reaching the destination URL. During this process, the system downloads and
compiles the PAC (Proxy Auto-Configuration) script in memory and tries to execute the FindProxyForURL function as
per the PAC specification.
When doing so, the system creates an internal application domain inside the application which runs with minimal
permissions, and, most importantly, it does not grant the UI permission to this new application domain. The evaluation
of a proxy and running the FindProxyForURL javascript function happens in the context of this new application domain
and during this process the system may need to run several helper functions as per the PAC specification.
IWebRequestCreate IWebRequestCreate Interface
Provides the base interface for creating WebRequest instances.

D eclaration
public interface IWebRequestCreate
type IWebRequestCreate = interface

I nheritance H ierarchy
None

Remarks
The IWebRequestCreate interface defines the method that WebRequest descendants must use to register with the
WebRequest.Create method.
Classes that implement the IWebRequestCreate interface can be registered with the WebRequest class and associated
with a specific URI scheme so that the WebRequest calls the class's Create method when a URI that matches that
scheme is requested.

Methods
Create(Uri)
Create(Uri)

Creates a WebRequest instance.


IWebRequestCreate.Create IWebRequestCreate.Create
I n this Article
Creates a WebRequest instance.
public System.Net.WebRequest Create (Uri uri);
abstract member Create : Uri -> System.Net.WebRequest

Parameters
uri Uri Uri
The uniform resource identifier (URI) of the Web resource.
Returns
WebRequest WebRequest
A WebRequest instance.
Exceptions
NotSupportedException NotSupportedException
The request scheme specified in uri is not supported by this IWebRequestCreate instance.
ArgumentNullException ArgumentNullException
uri is null .
UriFormatException UriFormatException
In the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, FormatException,
instead.
The URI specified in uri is not a valid URI.

Remarks
The Create method must return an initialized instance of the WebRequest descendant that is capable of performing a
standard request/response transaction for the protocol without needing any protocol-specific fields modified.
NetworkAccess NetworkAccess Enum
Specifies network access permissions.

D eclaration
[System.Flags]
public enum NetworkAccess
type NetworkAccess =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The NetworkAccess enumeration is used with the WebPermission and SocketPermission classes.

Fields
Accept Indicates that the application is allowed to accept connections from the Internet on a local resource. Notice that this
Accept is a protection for the local host that uses Accept to grant access to a local resource (address/port). At the time a
socket tries to bind to this local resource a permission check is performed to see if an Accept exists on that
resource.

Connect Indicates that the application is allowed to connect to specific Internet resources. Notice that, in the case of remote
Connect host resource, no check is performed to see that Connect permissions exist. This is because the port of a
connecting remote host is unknown and not suitable permissions can be built in advance. It is the application
responsibility to check the permissions of the remote host trying to connect to a listening socket.
NetworkCredential NetworkCredential Class
Provides credentials for password-based authentication schemes such as basic, digest, NTLM, and Kerberos
authentication.

D eclaration
public class NetworkCredential : System.Net.ICredentials, System.Net.ICredentialsByHost
type NetworkCredential = class
interface ICredentials
interface ICredentialsByHost

I nheritance H ierarchy
Object Object

Remarks
The NetworkCredential class is a base class that supplies credentials in password-based authentication schemes such
as basic, digest, NTLM, and Kerberos. Classes that implement the ICredentials interface, such as the CredentialCache
class, return NetworkCredential objects.
This class does not support public key-based authentication methods such as Secure Sockets Layer (SSL ) client
authentication.

Constructors
NetworkCredential()
NetworkCredential()

Initializes a new instance of the NetworkCredential class.

NetworkCredential(String, SecureString)
NetworkCredential(String, SecureString)

Initializes a new instance of the NetworkCredential class with the specified user name and password.

NetworkCredential(String, String)
NetworkCredential(String, String)

Initializes a new instance of the NetworkCredential class with the specified user name and password.

NetworkCredential(String, SecureString, String)


NetworkCredential(String, SecureString, String)

Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain.

NetworkCredential(String, String, String)


NetworkCredential(String, String, String)
Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain.

Properties
Domain
Domain

Gets or sets the domain or computer name that verifies the credentials.

Password
Password

Gets or sets the password for the user name associated with the credentials.

SecurePassword
SecurePassword

Gets or sets the password as a SecureString instance.

UserName
UserName

Gets or sets the user name associated with the credentials.

Methods
GetCredential(Uri, String)
GetCredential(Uri, String)

Returns an instance of the NetworkCredential class for the specified Uniform Resource Identifier (URI) and
authentication type.

GetCredential(String, Int32, String)


GetCredential(String, Int32, String)

Returns an instance of the NetworkCredential class for the specified host, port, and authentication type.
NetworkCredential.Domain NetworkCredential.Domain
I n this Article
Gets or sets the domain or computer name that verifies the credentials.
public string Domain { get; set; }
member this.Domain : string with get, set

Returns
String String
The name of the domain associated with the credentials.

Examples
The following code example uses the Domain property to set the domain associated with the credentials.
// Create an empty instance of the NetworkCredential class.
NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = passwd;

// Create a WebRequest with the specified URL.


WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentials;
Console.WriteLine("

User Credentials:- Domain : {0} , UserName : {1} , Password :


{2}",myCredentials.Domain,myCredentials.UserName,myCredentials.Password);

// Send the request and wait for a response.


Console.WriteLine("

Request to Url is sent.Waiting for response...Please wait ...");


WebResponse myWebResponse = myWebRequest.GetResponse();

// Process the response.


Console.WriteLine("
Response received sucessfully");

// Release the resources of the response object.


myWebResponse.Close();

Remarks
The Domain property specifies the domain or realm to which the user name belongs. Typically, this is the host
computer name where the application runs or the user domain for the currently logged in user.
NetworkCredential.GetCredential NetworkCredential.Get
Credential
I n this Article

Overloads
GetCredential(Uri, String) GetCredential(Uri, String)
Returns an instance of the NetworkCredential class for the
specified Uniform Resource Identifier (URI) and authentication
type.

GetCredential(String, Int32, String) GetCredential(String, Int32,


String) Returns an instance of the NetworkCredential class for the
specified host, port, and authentication type.

GetCredential(Uri, String) GetCredential(Uri, String)


Returns an instance of the NetworkCredential class for the specified Uniform Resource Identifier (URI) and
authentication type.
public System.Net.NetworkCredential GetCredential (Uri uri, string authType);
abstract member GetCredential : Uri * string -> System.Net.NetworkCredential
override this.GetCredential : Uri * string -> System.Net.NetworkCredential

Parameters
uri Uri Uri
The URI that the client provides authentication for.
authType String String
The type of authentication requested, as defined in the AuthenticationType property.
Returns
NetworkCredential NetworkCredential
A NetworkCredential object.
Examples
The following code example uses the GetCredential method to retrieve a NetworkCredential object for the specified
URI.
// Create an empty instance of the NetworkCredential class.
NetworkCredential myCredentials = new NetworkCredential(userName,password);
// Create a webrequest with the specified URL.
WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentials.GetCredential(new Uri(url),"");
Console.WriteLine("

User Credentials:- UserName : {0} , Password : {1}",myCredentials.UserName,myCredentials.Password);


// Send the request and wait for a response.
Console.WriteLine("

Request to Url is sent.Waiting for response...Please wait ...");


WebResponse myWebResponse = myWebRequest.GetResponse();
// Process the response.
Console.WriteLine("
Response received sucessfully");
// Release the resources of the response object.
myWebResponse.Close();

GetCredential(String, Int32, String) GetCredential(String, Int32,


String)
Returns an instance of the NetworkCredential class for the specified host, port, and authentication type.

public System.Net.NetworkCredential GetCredential (string host, int port, string


authenticationType);
abstract member GetCredential : string * int * string -> System.Net.NetworkCredential
override this.GetCredential : string * int * string -> System.Net.NetworkCredential

Parameters
host String String
The host computer that authenticates the client.
port Int32 Int32
The port on the host that the client communicates with.

authenticationType String String


The type of authentication requested, as defined in the AuthenticationType property.
Returns
NetworkCredential NetworkCredential
A NetworkCredential for the specified host, port, and authentication protocol, or null if there are no credentials
available for the specified host, port, and authentication protocol.
Remarks
The value of authType corresponds to the IAuthenticationModule.AuthenticationType property.
NetworkCredential NetworkCredential
I n this Article

Overloads
NetworkCredential()
Initializes a new instance of the NetworkCredential class.

NetworkCredential(String, SecureString) NetworkCredential(


String, SecureString) Initializes a new instance of the NetworkCredential class with
the specified user name and password.

NetworkCredential(String, String) NetworkCredential(String,


String) Initializes a new instance of the NetworkCredential class with
the specified user name and password.

NetworkCredential(String, SecureString, String) Network


Credential(String, SecureString, String) Initializes a new instance of the NetworkCredential class with
the specified user name, password, and domain.

NetworkCredential(String, String, String) NetworkCredential(


String, String, String) Initializes a new instance of the NetworkCredential class with
the specified user name, password, and domain.

NetworkCredential()
Initializes a new instance of the NetworkCredential class.
public NetworkCredential ();

Remarks
The default constructor for the NetworkCredential class initializes all properties to null .

NetworkCredential(String, SecureString)
NetworkCredential(String, SecureString)
Initializes a new instance of the NetworkCredential class with the specified user name and password.
[System.CLSCompliant(false)]
public NetworkCredential (string userName, System.Security.SecureString password);
new System.Net.NetworkCredential : string * System.Security.SecureString ->
System.Net.NetworkCredential

Parameters
userName String String
The user name associated with the credentials.
password SecureString SecureString
The password for the user name associated with the credentials.
Attributes CLSCompliantAttribute
Exceptions
NotSupportedException NotSupportedException
The SecureString class is not supported on this platform.
Remarks
The constructor initializes a NetworkCredential object with the UserName property set to userName and the Password
property set to password .
The password parameter is a SecureString instance.
If this constructor is called with the password parameter set to null , a new instance of SecureString is initialized, If
secure strings are not supported on this platform, then the NotSupportedException is thrown

NetworkCredential(String, String) NetworkCredential(String,


String)
Initializes a new instance of the NetworkCredential class with the specified user name and password.
public NetworkCredential (string userName, string password);
new System.Net.NetworkCredential : string * string -> System.Net.NetworkCredential

Parameters
userName String String
The user name associated with the credentials.
password String String
The password for the user name associated with the credentials.
Examples
The following code example creates a NetworkCredential object using the specified user name and password.
// Call the onstructor to create an instance of NetworkCredential with the
// specified user name and password.
NetworkCredential myCredentials = new NetworkCredential(username,passwd);

// Create a WebRequest with the specified URL.


WebRequest myWebRequest = WebRequest.Create(url);
myCredentials.Domain = domain;
myWebRequest.Credentials = myCredentials;
Console.WriteLine("

Credentials Domain : {0} , UserName : {1} , Password : {2}",


myCredentials.Domain, myCredentials.UserName, myCredentials.Password);
Console.WriteLine("

Request to Url is sent.Waiting for response...");

// Send the request and wait for a response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Process the response.


Console.WriteLine("
Response received successfully.");
// Release the resources of the response object.
myWebResponse.Close();

Remarks
The constructor initializes a NetworkCredential object with the UserName property set to userName and the Password
property set to password .

NetworkCredential(String, SecureString, String)


NetworkCredential(String, SecureString, String)
Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain.
[System.CLSCompliant(false)]
public NetworkCredential (string userName, System.Security.SecureString password, string domain);
new System.Net.NetworkCredential : string * System.Security.SecureString * string ->
System.Net.NetworkCredential

Parameters
userName String String
The user name associated with the credentials.
password SecureString SecureString
The password for the user name associated with the credentials.
domain String String
The domain associated with these credentials.
Attributes CLSCompliantAttribute
Exceptions
NotSupportedException NotSupportedException
The SecureString class is not supported on this platform.
Remarks
The constructor initializes a NetworkCredential object with the UserName property set to userName , the Password
property set to password , and the Domain property set to domain .

The password parameter is a SecureString instance.

If this constructor is called with the password parameter set to null , a new instance of SecureString is initialized, If
secure strings are not supported on this platform, then the NotSupportedException is thrown

NetworkCredential(String, String, String)


NetworkCredential(String, String, String)
Initializes a new instance of the NetworkCredential class with the specified user name, password, and domain.

public NetworkCredential (string userName, string password, string domain);


new System.Net.NetworkCredential : string * string * string -> System.Net.NetworkCredential

Parameters
userName String String
The user name associated with the credentials.
password String String
The password for the user name associated with the credentials.
domain String String
The domain associated with these credentials.
Remarks
The constructor initializes a NetworkCredential object with the UserName property set to userName , the Password
property set to password , and the Domain property set to domain .
NetworkCredential.Password NetworkCredential.
Password
I n this Article
Gets or sets the password for the user name associated with the credentials.

public string Password { get; set; }


member this.Password : string with get, set

Returns
String String
The password associated with the credentials. If this NetworkCredential instance was initialized with the password
parameter set to null , then the Password property will return an empty string.

Examples
The following code example uses the Password property to set the password associated with the credentials.
// Create an empty instance of the NetworkCredential class.
NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = passwd;

// Create a WebRequest with the specified URL.


WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentials;
Console.WriteLine("

User Credentials:- Domain : {0} , UserName : {1} , Password :


{2}",myCredentials.Domain,myCredentials.UserName,myCredentials.Password);

// Send the request and wait for a response.


Console.WriteLine("

Request to Url is sent.Waiting for response...Please wait ...");


WebResponse myWebResponse = myWebRequest.GetResponse();

// Process the response.


Console.WriteLine("
Response received sucessfully");

// Release the resources of the response object.


myWebResponse.Close();
NetworkCredential.SecurePassword NetworkCredential.
SecurePassword
I n this Article
Gets or sets the password as a SecureString instance.

[System.CLSCompliant(false)]
public System.Security.SecureString SecurePassword { get; set; }
member this.SecurePassword : System.Security.SecureString with get, set

Returns
SecureString SecureString
The password for the user name associated with the credentials.
Attributes CLSCompliantAttribute
Exceptions
NotSupportedException NotSupportedException
The SecureString class is not supported on this platform.

Remarks
If an application attempts to set the SecurePassword property to null , a new instance of SecureString is initialized, If
secure strings are not supported on this platform, then the NotSupportedException is thrown
NetworkCredential.UserName NetworkCredential.User
Name
I n this Article
Gets or sets the user name associated with the credentials.

public string UserName { get; set; }


member this.UserName : string with get, set

Returns
String String
The user name associated with the credentials.

Examples
The following code example uses the UserName property to set the user name associated with the credentials.
// Create an empty instance of the NetworkCredential class.
NetworkCredential myCredentials = new NetworkCredential("","","");
myCredentials.Domain = domain;
myCredentials.UserName = username;
myCredentials.Password = passwd;

// Create a WebRequest with the specified URL.


WebRequest myWebRequest = WebRequest.Create(url);
myWebRequest.Credentials = myCredentials;
Console.WriteLine("

User Credentials:- Domain : {0} , UserName : {1} , Password :


{2}",myCredentials.Domain,myCredentials.UserName,myCredentials.Password);

// Send the request and wait for a response.


Console.WriteLine("

Request to Url is sent.Waiting for response...Please wait ...");


WebResponse myWebResponse = myWebRequest.GetResponse();

// Process the response.


Console.WriteLine("
Response received sucessfully");

// Release the resources of the response object.


myWebResponse.Close();
NetworkProgressChangedEventArgs NetworkProgress
ChangedEventArgs Class
Provides data for the network progress changed event.

D eclaration
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be
used directly from your code.", true)]
public class NetworkProgressChangedEventArgs : System.ComponentModel.ProgressChangedEventArgs
type NetworkProgressChangedEventArgs = class
inherit ProgressChangedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
ProgressChangedEventArgs ProgressChangedEventArgs

Constructors
NetworkProgressChangedEventArgs(Int32, Int32, Int32, Object)
NetworkProgressChangedEventArgs(Int32, Int32, Int32, Object)

Initializes a new instance of the NetworkProgressChangedEventArgs class

Properties
ProcessedBytes
ProcessedBytes

Gets the number of bytes that have been processed.

TotalBytes
TotalBytes

Gets the total number of bytes that have been transferred.


NetworkProgressChangedEventArgs NetworkProgress
ChangedEventArgs
I n this Article
Initializes a new instance of the NetworkProgressChangedEventArgs class

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public NetworkProgressChangedEventArgs (int percentage, int processedBytes, int totalBytes, object
userState);
new System.Net.NetworkProgressChangedEventArgs : int * int * int * obj ->
System.Net.NetworkProgressChangedEventArgs

Parameters
percentage Int32 Int32
The percentage of an asynchronous task that has been completed.
processedBytes Int32 Int32
The number of processed bytes.
totalBytes Int32 Int32
The total number of bytes.
userState Object Object
A unique user state.
Attributes ObsoleteAttribute
NetworkProgressChangedEventArgs.ProcessedBytes
NetworkProgressChangedEventArgs.ProcessedBytes
I n this Article
Gets the number of bytes that have been processed.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public int ProcessedBytes { get; }
member this.ProcessedBytes : int

Returns
Int32 Int32
Returns Int32.
The number of bytes processed.
Attributes ObsoleteAttribute
NetworkProgressChangedEventArgs.TotalBytes Network
ProgressChangedEventArgs.TotalBytes
I n this Article
Gets the total number of bytes that have been transferred.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public int TotalBytes { get; }
member this.TotalBytes : int

Returns
Int32 Int32
Returns Int32.
The total number of bytes transferred.
Attributes ObsoleteAttribute
OpenReadCompletedEventArgs OpenReadCompleted
EventArgs Class
Provides data for the OpenReadCompleted event.

D eclaration
public class OpenReadCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type OpenReadCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to OpenReadCompletedEventHandler methods.

Properties
Result
Result

Gets a readable stream that contains data downloaded by a DownloadDataAsync method.


OpenReadCompletedEventArgs.Result OpenRead
CompletedEventArgs.Result
I n this Article
Gets a readable stream that contains data downloaded by a DownloadDataAsync method.

public System.IO.Stream Result { get; }


member this.Result : System.IO.Stream

Returns
Stream Stream
A Stream that contains the downloaded data.

Examples
The following code example uses the stream returned by this property.
private static void OpenReadCallback2 (Object sender, OpenReadCompletedEventArgs e)
{
Stream reply = null;
StreamReader s = null;

try
{
reply = (Stream)e.Result;
s = new StreamReader (reply);
Console.WriteLine (s.ReadToEnd ());
}
finally
{
if (s != null)
{
s.Close ();
}

if (reply != null)
{
reply.Close ();
}
}
}

Remarks
You should check the Error and Cancelled properties before using the data that is returned by this property. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
OpenReadCompletedEventHandler OpenRead
CompletedEventHandler Delegate
Represents the method that will handle the OpenReadCompleted event of a WebClient.

D eclaration
public delegate void OpenReadCompletedEventHandler(object sender, OpenReadCompletedEventArgs e);
type OpenReadCompletedEventHandler = delegate of obj * OpenReadCompletedEventArgs -> unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a OpenReadCompletedEventHandler delegate, you identify the method that will handle the event. To
associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate.
OpenWriteCompletedEventArgs OpenWriteCompleted
EventArgs Class
Provides data for the OpenWriteCompleted event.

D eclaration
public class OpenWriteCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type OpenWriteCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to OpenWriteCompletedEventHandler methods.

Properties
Result
Result

Gets a writable stream that is used to send data to a server.


OpenWriteCompletedEventArgs.Result OpenWrite
CompletedEventArgs.Result
I n this Article
Gets a writable stream that is used to send data to a server.

public System.IO.Stream Result { get; }


member this.Result : System.IO.Stream

Returns
Stream Stream
A Stream where you can write data to be uploaded.

Examples
The following code example uses the stream returned by this property.
private static void OpenWriteCallback2 (Object sender, OpenWriteCompletedEventArgs e)
{
Stream body = null;
StreamWriter s = null;

try
{
body = (Stream)e.Result;
s = new StreamWriter (body);
s.AutoFlush = true;
s.Write ("This is content data to be sent to the server.");
}
finally
{
if (s != null)
{
s.Close ();
}

if (body != null)
{
body.Close ();
}
}
}

Remarks
You should check the Error and Cancelled properties before using the stream returned by this property. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
OpenWriteCompletedEventHandler OpenWrite
CompletedEventHandler Delegate
Represents the method that will handle the OpenWriteCompleted event of a WebClient.

D eclaration
public delegate void OpenWriteCompletedEventHandler(object sender, OpenWriteCompletedEventArgs
e);
type OpenWriteCompletedEventHandler = delegate of obj * OpenWriteCompletedEventArgs -> unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a OpenWriteCompletedEventHandler delegate, you identify the method that will handle the event. To
associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate.
ProtocolViolationException ProtocolViolationException
Class
The exception that is thrown when an error is made while using a network protocol.

D eclaration
[System.Serializable]
public class ProtocolViolationException : InvalidOperationException
type ProtocolViolationException = class
inherit InvalidOperationException
interface ISerializable

I nheritance H ierarchy
Object Object
Exception Exception
SystemException SystemException
InvalidOperationException InvalidOperationException

Remarks
A ProtocolViolationException is thrown by descendants of WebRequest and WebResponse to indicate an error using
the underlying protocol. For example, the HttpWebRequest and HttpWebResponse classes throw a
ProtocolViolationException to indicate an error using HTTP.

Constructors
ProtocolViolationException()
ProtocolViolationException()

Initializes a new instance of the ProtocolViolationException class.

ProtocolViolationException(String)
ProtocolViolationException(String)

Initializes a new instance of the ProtocolViolationException class with the specified message.

ProtocolViolationException(SerializationInfo, StreamingContext)
ProtocolViolationException(SerializationInfo, StreamingContext)

Initializes a new instance of the ProtocolViolationException class from the specified SerializationInfo and
StreamingContext instances.

Methods
GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data required to serialize the target object.
ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Serializes this instance into the specified SerializationInfo object.


ProtocolViolationException.GetObjectData Protocol
ViolationException.GetObjectData
I n this Article
Populates a SerializationInfo with the data required to serialize the target object.

public override void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
ProtocolViolationException.ISerializable.GetObjectData
I n this Article
Serializes this instance into the specified SerializationInfo object.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The object into which this ProtocolViolationException will be serialized.
streamingContext StreamingContext
The destination of the serialization.
ProtocolViolationException ProtocolViolationException
I n this Article

Overloads
ProtocolViolationException()
Initializes a new instance of the ProtocolViolationException
class.

ProtocolViolationException(String) ProtocolViolationException(
String) Initializes a new instance of the ProtocolViolationException
class with the specified message.

ProtocolViolationException(SerializationInfo, Streaming
Context) ProtocolViolationException(SerializationInfo, Initializes a new instance of the ProtocolViolationException
StreamingContext) class from the specified SerializationInfo and StreamingContext
instances.

ProtocolViolationException()
Initializes a new instance of the ProtocolViolationException class.
public ProtocolViolationException ();

Remarks
The Message property is initialized to a system-supplied message that describes the error. The InnerException property
is initialized to null .

ProtocolViolationException(String)
ProtocolViolationException(String)
Initializes a new instance of the ProtocolViolationException class with the specified message.
public ProtocolViolationException (string message);
new System.Net.ProtocolViolationException : string -> System.Net.ProtocolViolationException

Parameters
message String String
The error message string.
Remarks
This constructor initializes a new instance of the ProtocolViolationException class with the Message property set to the
value of the message parameter. If message is a null reference, the Message property is initialized to a system-supplied
message. The InnerException property is initialized to null .

ProtocolViolationException(SerializationInfo, StreamingContext)
ProtocolViolationException(SerializationInfo, StreamingContext)
Initializes a new instance of the ProtocolViolationException class from the specified SerializationInfo and
StreamingContext instances.
protected ProtocolViolationException (System.Runtime.Serialization.SerializationInfo
serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.ProtocolViolationException : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.ProtocolViolationException

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo that contains the information that is required to deserialize the ProtocolViolationException.
streamingContext StreamingContext StreamingContext
A StreamingContext that contains the source of the serialized stream that is associated with the new
ProtocolViolationException.
Remarks
This constructor implements the ISerializable interface for the ProtocolViolationException class.
See ISerializableISerializable
Also
SecurityProtocolType SecurityProtocolType Enum
Specifies the security protocols that are supported by the Schannel security package.

D eclaration
[System.Flags]
public enum SecurityProtocolType
type SecurityProtocolType =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
This enumeration defines the set of values that you can use to specify which transport security protocol to use. It is the
enumerated type for the SecurityProtocol property. Use this enumeration to determine your transport security
protocol policy when you're using HTTP APIs in the .NET Framework such as WebClient, HttpWebRequest, HttpClient,
and SmtpClient (when using TLS/SSL ).
The Transport Layer Security (TLS ) protocols assume that a connection-oriented protocol, typically TCP, is in use.

Fields
Ssl3 Ssl3 Specifies the Secure Socket Layer (SSL) 3.0 security protocol. SSL 3.0 has been superseded by the
Transport Layer Security (TLS) protocol and is provided for backward compatibility only.

SystemDefault Allows the operating system to choose the best protocol to use, and to block protocols that are not
SystemDefault secure. Unless your app has a specific reason not to, you should use this value.

Tls Tls Specifies the Transport Layer Security (TLS) 1.0 security protocol. The TLS 1.0 protocol is defined in IETF
RFC 2246.

Tls11 Tls11 Specifies the Transport Layer Security (TLS) 1.1 security protocol. The TLS 1.1 protocol is defined in IETF
RFC 4346. On Windows systems, this value is supported starting with Windows 7.

Tls12 Tls12 Specifies the Transport Layer Security (TLS) 1.2 security protocol. The TLS 1.2 protocol is defined in IETF
RFC 5246. On Windows systems, this value is supported starting with Windows 7.

Tls13 Tls13 Specifies the TLS 1.3 security protocol. The TLS protocol is defined in IETF RFC 8446.
ServicePoint ServicePoint Class
Provides connection management for HTTP connections.

D eclaration
public class ServicePoint
type ServicePoint = class

I nheritance H ierarchy
Object Object

Remarks
The ServicePoint class handles connections to an Internet resource based on the host information passed in the
resource's Uniform Resource Identifier (URI). The initial connection to the resource determines the information that the
ServicePoint object maintains, which is then shared by all subsequent requests to that resource.
ServicePoint objects are managed by the ServicePointManager class and are created, if necessary, by the
ServicePointManager.FindServicePoint method. ServicePoint objects are never created directly but are always created
and managed by the ServicePointManager class. The maximum number of ServicePoint objects that can be created is
set by the ServicePointManager.MaxServicePoints property.
Each ServicePoint object maintains its connection to an Internet resource until it has been idle longer than the time
specified in the MaxIdleTime property. When a ServicePoint exceeds the MaxIdleTime value, it can be recycled to
another connection. The default value of MaxIdleTime is set by the ServicePointManager.MaxServicePointIdleTime
property.
When the ConnectionLeaseTimeout property is set to a value other than -1, and after the specified time elapses, an
active ServicePoint connection is closed after it services the next request. This is useful for applications that do not
require active connections that are opened indefinitely, as they are by default.
Note

In high load conditions, some applications may run out of free threads in the ThreadPool, which may lead to poor
system performance (such as high and variable transaction times).

Properties
Address
Address

Gets the Uniform Resource Identifier (URI) of the server that this ServicePoint object connects to.

BindIPEndPointDelegate
BindIPEndPointDelegate

Specifies the delegate to associate a local IPEndPoint with a ServicePoint.

Certificate
Certificate
Gets the certificate received for this ServicePoint object.

ClientCertificate
ClientCertificate

Gets the last client certificate sent to the server.

ConnectionLeaseTimeout
ConnectionLeaseTimeout

Gets or sets the number of milliseconds after which an active ServicePoint connection is closed.

ConnectionLimit
ConnectionLimit

Gets or sets the maximum number of connections allowed on this ServicePoint object.

ConnectionName
ConnectionName

Gets the connection name.

CurrentConnections
CurrentConnections

Gets the number of open connections associated with this ServicePoint object.

Expect100Continue
Expect100Continue

Gets or sets a Boolean value that determines whether 100-Continue behavior is used.

IdleSince
IdleSince

Gets the date and time that the ServicePoint object was last connected to a host.

MaxIdleTime
MaxIdleTime

Gets or sets the amount of time a connection associated with the ServicePoint object can remain idle before the
connection is closed.
ProtocolVersion
ProtocolVersion

Gets the version of the HTTP protocol that the ServicePoint object uses.

ReceiveBufferSize
ReceiveBufferSize

Gets or sets the size of the receiving buffer for the socket used by this ServicePoint.

SupportsPipelining
SupportsPipelining

Indicates whether the ServicePoint object supports pipelined connections.

UseNagleAlgorithm
UseNagleAlgorithm

Gets or sets a Boolean value that determines whether the Nagle algorithm is used on connections managed by
this ServicePoint object.

Methods
CloseConnectionGroup(String)
CloseConnectionGroup(String)

Removes the specified connection group from this ServicePoint object.

GetHashCode()
GetHashCode()

Returns a hash value for a ServicePoint instance.

SetTcpKeepAlive(Boolean, Int32, Int32)


SetTcpKeepAlive(Boolean, Int32, Int32)

Enables or disables the keep-alive option on a TCP connection.


ServicePoint.Address ServicePoint.Address
I n this Article
Gets the Uniform Resource Identifier (URI) of the server that this ServicePoint object connects to.
public Uri Address { get; }
member this.Address : Uri

Returns
Uri Uri
An instance of the Uri class that contains the URI of the Internet server that this ServicePoint object connects to.
Exceptions
NotSupportedException NotSupportedException
The ServicePoint is in host mode.

Examples
The following code example displays the value of this property.
// Display the ServicePoint Internet resource address.
Console.WriteLine("Address = {0} ", sp.Address.ToString());
ServicePoint.BindIPEndPointDelegate ServicePoint.BindIP
EndPointDelegate
I n this Article
Specifies the delegate to associate a local IPEndPoint with a ServicePoint.

public System.Net.BindIPEndPoint BindIPEndPointDelegate { get; set; }


member this.BindIPEndPointDelegate : System.Net.BindIPEndPoint with get, set

Returns
BindIPEndPoint BindIPEndPoint
A delegate that forces a ServicePoint to use a particular local Internet Protocol (IP ) address and port number. The
default value is null .

Remarks
Some load balancing techniques require a client to use a specific local IP address and port number, rather than
IPAddress.Any (or IPAddress.IPv6Any for Internet Protocol Version 6) and an ephemeral port. Your
BindIPEndPointDelegate can satisfy this requirement.
ServicePoint.Certificate ServicePoint.Certificate
I n this Article
Gets the certificate received for this ServicePoint object.
public System.Security.Cryptography.X509Certificates.X509Certificate Certificate { get; }
member this.Certificate : System.Security.Cryptography.X509Certificates.X509Certificate

Returns
X509Certificate X509Certificate
An instance of the X509Certificate class that contains the security certificate received for this ServicePoint object.

Examples
The following code example displays the value of this property.
if (sp.Certificate == null)
Console.WriteLine("Certificate = (null)");
else
Console.WriteLine("Certificate = " + sp.Certificate.ToString());

if (sp.ClientCertificate == null)
Console.WriteLine("ClientCertificate = (null)");
else
Console. WriteLine("ClientCertificate = " + sp.ClientCertificate.ToString());

Console.WriteLine("ProtocolVersion = " + sp.ProtocolVersion.ToString());


Console.WriteLine("SupportsPipelining = " + sp.SupportsPipelining);

Remarks
Although a ServicePoint object can make multiple connections to an Internet resource, it can maintain only one
certificate.
ServicePoint.ClientCertificate ServicePoint.Client
Certificate
I n this Article
Gets the last client certificate sent to the server.

public System.Security.Cryptography.X509Certificates.X509Certificate ClientCertificate { get; }


member this.ClientCertificate : System.Security.Cryptography.X509Certificates.X509Certificate

Returns
X509Certificate X509Certificate
An X509Certificate object that contains the public values of the last client certificate sent to the server.

Examples
The following code example displays the value of this property.
if (sp.Certificate == null)
Console.WriteLine("Certificate = (null)");
else
Console.WriteLine("Certificate = " + sp.Certificate.ToString());

if (sp.ClientCertificate == null)
Console.WriteLine("ClientCertificate = (null)");
else
Console. WriteLine("ClientCertificate = " + sp.ClientCertificate.ToString());

Console.WriteLine("ProtocolVersion = " + sp.ProtocolVersion.ToString());


Console.WriteLine("SupportsPipelining = " + sp.SupportsPipelining);
ServicePoint.CloseConnectionGroup ServicePoint.Close
ConnectionGroup
I n this Article
Removes the specified connection group from this ServicePoint object.

public bool CloseConnectionGroup (string connectionGroupName);


member this.CloseConnectionGroup : string -> bool

Parameters
connectionGroupName String String
The name of the connection group that contains the connections to close and remove from this service point.
Returns
Boolean Boolean
A Boolean value that indicates whether the connection group was closed.

Remarks
Connection groups associate a set of requests with a particular connection or set of connections. This method removes
and closes all connections that belong to the specified connection group.
ServicePoint.ConnectionLeaseTimeout ServicePoint.
ConnectionLeaseTimeout
I n this Article
Gets or sets the number of milliseconds after which an active ServicePoint connection is closed.

public int ConnectionLeaseTimeout { get; set; }


member this.ConnectionLeaseTimeout : int with get, set

Returns
Int32 Int32
A Int32 that specifies the number of milliseconds that an active ServicePoint connection remains open. The default is -
1, which allows an active ServicePoint connection to stay connected indefinitely. Set this property to 0 to force
ServicePoint connections to close after servicing a request.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for a set operation is a negative number less than -1.

Examples
The following code example sets the value of this property.
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Examples.System.Net
{
public class ServicePointExample
{
// Pass in the name of the Web page to retrieve.
public static void Main(string[] args)
{
string page;
if (args == null || args.Length == 0 || args[0].Length == 0)
{
page = "http://www.contoso.com/default.html";
}
else
{
page = args[0];
}
// Create the request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(page);
// Get the service point that handles the request's socket connection.
ServicePoint point = request.ServicePoint;
// Set the receive buffer size on the underlying socket.
point.ReceiveBufferSize = 2048;
// Set the connection lease timeout to infinite.
point.ConnectionLeaseTimeout = Timeout.Infinite;
// Send the request.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader s = new StreamReader(responseStream);
// Display the response.
Console.WriteLine(s.ReadToEnd());
s.Close();
responseStream.Close();
response.Close();
}
}
}

Remarks
You can use this property to ensure that a ServicePoint object's active connections do not remain open indefinitely. This
property is intended for scenarios where connections should be dropped and reestablished periodically, such as load
balancing scenarios.
By default, when KeepAlive is true for a request, the MaxIdleTime property sets the time-out for closing ServicePoint
connections due to inactivity. If the ServicePoint has active connections, MaxIdleTime has no effect and the connections
remain open indefinitely.
When the ConnectionLeaseTimeout property is set to a value other than -1, and after the specified time elapses, an
active ServicePoint connection is closed after servicing a request by setting KeepAlive to false in that request.
Setting this value affects all connections managed by the ServicePoint object.
ServicePoint.ConnectionLimit ServicePoint.Connection
Limit
I n this Article
Gets or sets the maximum number of connections allowed on this ServicePoint object.

public int ConnectionLimit { get; set; }


member this.ConnectionLimit : int with get, set

Returns
Int32 Int32
The maximum number of connections allowed on this ServicePoint object.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The connection limit is equal to or less than 0.

Examples
The following code example uses the ConnectionLimit property to check the maximum number of connections that the
ServicePoint object can make to the specified Uniform Resource Identifier (URI).
Console.WriteLine("ConnectionName = " + sp.ConnectionName);

// Display the maximum number of connections allowed on this


// ServicePoint instance.
Console.WriteLine("ConnectionLimit = " + sp.ConnectionLimit);

// Display the number of connections associated with this


// ServicePoint instance.
Console.WriteLine("CurrentConnections = " + sp.CurrentConnections);

Remarks
The ConnectionLimit property sets the maximum number of connections that the ServicePoint object can make to an
Internet resource. The value of the ConnectionLimit property is set to the value of the
ServicePointManager.DefaultConnectionLimit property when the ServicePoint object is created; subsequent changes
to DefaultConnectionLimit have no effect on existing ServicePoint objects.
See Managing Connections
Also
ServicePoint.ConnectionName ServicePoint.Connection
Name
I n this Article
Gets the connection name.

public string ConnectionName { get; }


member this.ConnectionName : string

Returns
String String
A String that represents the connection name.

Examples
Console.WriteLine("ConnectionName = " + sp.ConnectionName);

// Display the maximum number of connections allowed on this


// ServicePoint instance.
Console.WriteLine("ConnectionLimit = " + sp.ConnectionLimit);

// Display the number of connections associated with this


// ServicePoint instance.
Console.WriteLine("CurrentConnections = " + sp.CurrentConnections);

Remarks
If the ServicePoint object was constructed by calling a FindServicePoint overload with a Uri argument, then the
ConnectionName property represents the Scheme property of the Uri object used.
If the ServicePoint object was constructed from a network host and port, the ConnectionName property contains a
string that represents the host and the network port. If the ConnectionName property is set when constructed from a
host and port, only WebRequest objects with the same ConnectionGroupName value can use this ServicePoint object.
See Connection Grouping
Also
ServicePoint.CurrentConnections ServicePoint.Current
Connections
I n this Article
Gets the number of open connections associated with this ServicePoint object.

public int CurrentConnections { get; }


member this.CurrentConnections : int

Returns
Int32 Int32
The number of open connections associated with this ServicePoint object.

Examples
The following code example uses the CurrentConnections property to determine the number of open Internet
connections associated with this ServicePoint object.
// Display the ServicePoint Internet resource address.
Console.WriteLine("Address = {0} ", sp.Address.ToString());

Remarks
The CurrentConnections property contains the number of open Internet connections associated with this ServicePoint
object. The value of CurrentConnections cannot exceed that of ConnectionLimit.
ServicePoint.Expect100Continue ServicePoint.Expect100
Continue
I n this Article
Gets or sets a Boolean value that determines whether 100-Continue behavior is used.

public bool Expect100Continue { get; set; }


member this.Expect100Continue : bool with get, set

Returns
Boolean Boolean
true to expect 100-Continue responses for POST requests; otherwise, false . The default value is true .

Examples
The following code example displays the value of this property.
Console.WriteLine("UseNagleAlgorithm = " + sp.UseNagleAlgorithm.ToString());
Console.WriteLine("Expect 100-continue = " + sp.Expect100Continue.ToString());

Remarks
When this property is set to true , client requests that use the POST method expect to receive a 100-Continue
response from the server to indicate that the client should send the data to be posted. This mechanism allows clients to
avoid sending large amounts of data over the network when the server, based on the request headers, intends to reject
the request.
For example, assume the Expect100Continue property is false . When the request is sent to the server, it includes the
data. If, after reading the request headers, the server requires authentication and sends a 401 response, the client must
resend the data with proper authentication headers.
If the Expect100Continue property is true , the request headers are sent to the server. If the server has not rejected the
request, it sends a 100-Continue response signaling that the data can be transmitted. If, as in the preceding example,
the server requires authentication, it sends the 401 response and the client has not unnecessarily transmitted the data.
Changing the value of this property does not affect existing connections. Only new connections created after the
change are affected.
The Expect 100-Continue behavior is fully described in IETF RFC 2616 Section 10.1.1.
ServicePoint.GetHashCode ServicePoint.GetHashCode
I n this Article
Returns a hash value for a ServicePoint instance.
public override int GetHashCode ();
override this.GetHashCode : unit -> int

Returns
Int32 Int32
An integer hash value.

Remarks
The GetHashCode method returns a hash code of this instance. This value can be used as a key in hash tables.
ServicePoint.IdleSince ServicePoint.IdleSince
I n this Article
Gets the date and time that the ServicePoint object was last connected to a host.
public DateTime IdleSince { get; }
member this.IdleSince : DateTime

Returns
DateTime DateTime
A DateTime object that contains the date and time at which the ServicePoint object was last connected.

Examples
The following code example uses the IdleSince property to set and retrieve the date and time that the ServicePoint
object was last connected to a host.
// Display the date and time that the ServicePoint was last
// connected to a host.
Console.WriteLine("IdleSince = " + sp.IdleSince.ToString());

// Display the maximum length of time that the ServicePoint instance


// is allowed to maintain an idle connection to an Internet
// resource before it is recycled for use in another connection.
Console.WriteLine("MaxIdleTime = " + sp.MaxIdleTime);

Remarks
The IdleSince property records the last date and time at which a service point was disconnected from a host. When the
difference between the current time and IdleSince exceeds the value of MaxIdleTime, the ServicePoint object is
available for recycling to another connection.
ServicePoint.MaxIdleTime ServicePoint.MaxIdleTime
I n this Article
Gets or sets the amount of time a connection associated with the ServicePoint object can remain idle before the
connection is closed.

public int MaxIdleTime { get; set; }


member this.MaxIdleTime : int with get, set

Returns
Int32 Int32
The length of time, in milliseconds, that a connection associated with the ServicePoint object can remain idle before it is
closed and reused for another connection.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
MaxIdleTime is set to less than Infinite or greater than MaxValue.

Examples
The following code example uses the MaxIdleTime property to set and retrieve the ServicePoint idle time.
// Display the date and time that the ServicePoint was last
// connected to a host.
Console.WriteLine("IdleSince = " + sp.IdleSince.ToString());

// Display the maximum length of time that the ServicePoint instance


// is allowed to maintain an idle connection to an Internet
// resource before it is recycled for use in another connection.
Console.WriteLine("MaxIdleTime = " + sp.MaxIdleTime);

Remarks
You can set MaxIdleTime to Timeout.Infinite to indicate that a connection associated with the ServicePoint object
should never time out.
The default value of the MaxIdleTime property is the value of the ServicePointManager.MaxServicePointIdleTime
property when the ServicePoint object is created. Subsequent changes to the MaxServicePointIdleTime property have
no effect on existing ServicePoint objects.
When the MaxIdleTime for a connection associated with a ServicePoint is exceeded, the connection remains open until
the application tries to use the connection. At that time, the Framework closes the connection and creates a new
connection to the remote host.
ServicePoint.ProtocolVersion ServicePoint.Protocol
Version
I n this Article
Gets the version of the HTTP protocol that the ServicePoint object uses.

public virtual Version ProtocolVersion { get; }


member this.ProtocolVersion : Version

Returns
Version Version
A Version object that contains the HTTP protocol version that the ServicePoint object uses.

Examples
The following code example displays the value of this property.
if (sp.Certificate == null)
Console.WriteLine("Certificate = (null)");
else
Console.WriteLine("Certificate = " + sp.Certificate.ToString());

if (sp.ClientCertificate == null)
Console.WriteLine("ClientCertificate = (null)");
else
Console. WriteLine("ClientCertificate = " + sp.ClientCertificate.ToString());

Console.WriteLine("ProtocolVersion = " + sp.ProtocolVersion.ToString());


Console.WriteLine("SupportsPipelining = " + sp.SupportsPipelining);

Remarks
The HTTP protocol versions are HTTP/1.0 and HTTP/1.1.
ServicePoint.ReceiveBufferSize ServicePoint.Receive
BufferSize
I n this Article
Gets or sets the size of the receiving buffer for the socket used by this ServicePoint.

public int ReceiveBufferSize { get; set; }


member this.ReceiveBufferSize : int with get, set

Returns
Int32 Int32
A Int32 that contains the size, in bytes, of the receive buffer. The default is 8192.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for a set operation is greater than MaxValue.

Examples
The following code example sets the value of this property.
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace Examples.System.Net
{
public class ServicePointExample
{
// Pass in the name of the Web page to retrieve.
public static void Main(string[] args)
{
string page;
if (args == null || args.Length == 0 || args[0].Length == 0)
{
page = "http://www.contoso.com/default.html";
}
else
{
page = args[0];
}
// Create the request.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(page);
// Get the service point that handles the request's socket connection.
ServicePoint point = request.ServicePoint;
// Set the receive buffer size on the underlying socket.
point.ReceiveBufferSize = 2048;
// Set the connection lease timeout to infinite.
point.ConnectionLeaseTimeout = Timeout.Infinite;
// Send the request.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader s = new StreamReader(responseStream);
// Display the response.
Console.WriteLine(s.ReadToEnd());
s.Close();
responseStream.Close();
response.Close();
}
}
}

Remarks
For additional information, see ReceiveBufferSize.
ServicePoint.SetTcpKeepAlive ServicePoint.SetTcpKeep
Alive
I n this Article
Enables or disables the keep-alive option on a TCP connection.

public void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval);


member this.SetTcpKeepAlive : bool * int * int -> unit

Parameters
enabled Boolean Boolean
If set to true, then the TCP keep-alive option on a TCP connection will be enabled using the specified keepAliveTime
and keepAliveInterval values.
If set to false, then the TCP keep-alive option is disabled and the remaining parameters are ignored.
The default value is false.
keepAliveTime Int32 Int32
Specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent.
The value must be greater than 0. If a value of less than or equal to zero is passed an ArgumentOutOfRangeException
is thrown.
keepAliveInterval Int32 Int32
Specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is
received.
The value must be greater than 0. If a value of less than or equal to zero is passed an ArgumentOutOfRangeException
is thrown.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for keepAliveTime or keepAliveInterval parameter is less than or equal to 0.

Remarks
An application can request that a TCP/IP provider enable the use of keep-alive packets on a TCP connection. The
default is that the use of keep-alive packets on a TCP connection is disabled.
The default settings when a TCP socket is initialized sets the keep-alive timeout to 2 hours and the keep-alive interval
to 1 second. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-
alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive
keep-alive packets are sent if no acknowledgement is received. The number of keep-alive probes cannot be changed
and is set to 10.
If a TCP connection is dropped as the result of keep-alives, a SocketError of NetworkReset is returned to any calls in
progress on the socket, and any subsequent calls will fail with a SocketError of NotConnected.
ServicePoint.SupportsPipelining ServicePoint.Supports
Pipelining
I n this Article
Indicates whether the ServicePoint object supports pipelined connections.

public bool SupportsPipelining { get; }


member this.SupportsPipelining : bool

Returns
Boolean Boolean
true if the ServicePoint object supports pipelined connections; otherwise, false .

Examples
The following code example displays the value of this property.
if (sp.Certificate == null)
Console.WriteLine("Certificate = (null)");
else
Console.WriteLine("Certificate = " + sp.Certificate.ToString());

if (sp.ClientCertificate == null)
Console.WriteLine("ClientCertificate = (null)");
else
Console. WriteLine("ClientCertificate = " + sp.ClientCertificate.ToString());

Console.WriteLine("ProtocolVersion = " + sp.ProtocolVersion.ToString());


Console.WriteLine("SupportsPipelining = " + sp.SupportsPipelining);

Remarks
Pipelining allows clients to send multiple requests across a persistent connection without waiting for each response
from the server. The server sends the responses in the same order as the requests were received.
Pipelining is described in detail in IETF RFC 2616 section 8.1.2.2.
ServicePoint.UseNagleAlgorithm ServicePoint.UseNagle
Algorithm
I n this Article
Gets or sets a Boolean value that determines whether the Nagle algorithm is used on connections managed by this
ServicePoint object.
public bool UseNagleAlgorithm { get; set; }
member this.UseNagleAlgorithm : bool with get, set

Returns
Boolean Boolean
true to use the Nagle algorithm; otherwise, false . The default value is true .

Examples
The following code example displays the value of this property.
Console.WriteLine("UseNagleAlgorithm = " + sp.UseNagleAlgorithm.ToString());
Console.WriteLine("Expect 100-continue = " + sp.Expect100Continue.ToString());

Remarks
The Nagle algorithm is used to buffer small packets of data and transmit them as a single packet. This process, referred
to as "nagling," is widely used because it reduces the number of packets transmitted and lowers the overhead per
packet.
Changing the value of this property does not affect existing connections. Only new connections created after the
change are affected.
The Nagle algorithm is fully described in IETF RFC 896.
ServicePointManager ServicePointManager Class
Manages the collection of ServicePoint objects.

D eclaration
public class ServicePointManager
type ServicePointManager = class

I nheritance H ierarchy
Object Object

Remarks
ServicePointManager is a static class used to create, maintain, and delete instances of the ServicePoint class.
When an application requests a connection to an Internet resource Uniform Resource Identifier (URI) through the
ServicePointManager object, the ServicePointManager returns a ServicePoint object that contains connection
information for the host and scheme identified by the URI. If there is an existing ServicePoint object for that host and
scheme, the ServicePointManager object returns the existing ServicePoint object; otherwise, the ServicePointManager
object creates a new ServicePoint object.
The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for
connections. Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FtpWebRequest,
SmtpClient, SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default.
Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services
or TLS w/ RC4 services. This article explains how to modify your code so that the new behavior is disabled.

Fields
DefaultNonPersistentConnectionLimit
DefaultNonPersistentConnectionLimit

The default number of non-persistent connections (4) allowed on a ServicePoint object connected to an HTTP/1.0
or later server. This field is constant but is no longer used in the .NET Framework 2.0.

DefaultPersistentConnectionLimit
DefaultPersistentConnectionLimit

The default number of persistent connections (2) allowed on a ServicePoint object connected to an HTTP/1.1 or
later server. This field is constant and is used to initialize the DefaultConnectionLimit property if the value of the
DefaultConnectionLimit property has not been set either directly or through configuration.

Properties
CertificatePolicy
CertificatePolicy

Gets or sets policy for server certificates.


CheckCertificateRevocationList
CheckCertificateRevocationList

Gets or sets a Boolean value that indicates whether the certificate is checked against the certificate authority
revocation list.

ClientCipherSuitesCallback
ClientCipherSuitesCallback

DefaultConnectionLimit
DefaultConnectionLimit

Gets or sets the maximum number of concurrent connections allowed by a ServicePoint object.

DnsRefreshTimeout
DnsRefreshTimeout

Gets or sets a value that indicates how long a Domain Name Service (DNS ) resolution is considered valid.

EnableDnsRoundRobin
EnableDnsRoundRobin

Gets or sets a value that indicates whether a Domain Name Service (DNS ) resolution rotates among the
applicable Internet Protocol (IP ) addresses.

EncryptionPolicy
EncryptionPolicy

Gets the EncryptionPolicy for this ServicePointManager instance.

Expect100Continue
Expect100Continue

Gets or sets a Boolean value that determines whether 100-Continue behavior is used.

MaxServicePointIdleTime
MaxServicePointIdleTime

Gets or sets the maximum idle time of a ServicePoint object.

MaxServicePoints
MaxServicePoints

Gets or sets the maximum number of ServicePoint objects to maintain at any time.
ReusePort
ReusePort

Setting this property value to true causes all outbound TCP connections from HttpWebRequest to use the native
socket option SO_REUSE_UNICASTPORT on the socket. This causes the underlying outgoing ports to be shared.
This is useful for scenarios where a large number of outgoing connections are made in a short time, and the app
risks running out of ports.

SecurityProtocol
SecurityProtocol

Gets or sets the security protocol used by the ServicePoint objects managed by the ServicePointManager object.

ServerCertificateValidationCallback
ServerCertificateValidationCallback

Gets or sets the callback to validate a server certificate.

ServerCipherSuitesCallback
ServerCipherSuitesCallback

UseNagleAlgorithm
UseNagleAlgorithm

Determines whether the Nagle algorithm is used by the service points managed by this ServicePointManager
object.

Methods
FindServicePoint(Uri, IWebProxy)
FindServicePoint(Uri, IWebProxy)

Finds an existing ServicePoint object or creates a new ServicePoint object to manage communications with the
specified Uri object.

FindServicePoint(Uri)
FindServicePoint(Uri)

Finds an existing ServicePoint object or creates a new ServicePoint object to manage communications with the
specified Uri object.

FindServicePoint(String, IWebProxy)
FindServicePoint(String, IWebProxy)

Finds an existing ServicePoint object or creates a new ServicePoint object to manage communications with the
specified Uniform Resource Identifier (URI).
SetTcpKeepAlive(Boolean, Int32, Int32)
SetTcpKeepAlive(Boolean, Int32, Int32)

Enables or disables the keep-alive option on a TCP connection.

See Also
ServicePoint ServicePoint
ServicePoint ServicePoint
ServicePointManager.CertificatePolicy ServicePoint
Manager.CertificatePolicy
I n this Article
Gets or sets policy for server certificates.

[System.Obsolete("Use ServerCertificateValidationCallback instead", false)]


[System.Obsolete("CertificatePolicy is obsoleted for this type, please use
ServerCertificateValidationCallback instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.ICertificatePolicy CertificatePolicy { get; set; }
member this.CertificatePolicy : System.Net.ICertificatePolicy with get, set

Returns
ICertificatePolicy ICertificatePolicy
An object that implements the ICertificatePolicy interface.
Attributes ObsoleteAttribute ObsoleteAttribute

Examples
The following code example shows how to catch a certificate policy exception for a custom certificate policy. It assumes
that the certificate policy object has been defined, that the Uniform Resource Identifier (URI) for the Web resource is
contained in the variable myUri , and that there is a method named ProcessResponse that performs the work of the
application.
ServicePointManager.CertificatePolicy = new MyCertificatePolicy();

// Create the request and receive the response


try
{
WebRequest myRequest = WebRequest.Create(myUri);
WebResponse myResponse = myRequest.GetResponse();
ProcessResponse(myResponse);
myResponse.Close();
}
// Catch any exceptions
catch (WebException e)
{
if (e.Status == WebExceptionStatus.TrustFailure)
{
// Code for handling security certificate problems goes here.
}
// Other exception handling goes here
}

Remarks
When the CertificatePolicy property is set to an ICertificatePolicy interface object, the ServicePointManager object uses
the certificate policy defined in that instance instead of the default certificate policy.
The default certificate policy allows valid certificates and valid certificates that have expired.
See ServicePointServicePoint
Also
ServicePointManager.CheckCertificateRevocationList
ServicePointManager.CheckCertificateRevocationList
I n this Article
Gets or sets a Boolean value that indicates whether the certificate is checked against the certificate authority revocation
list.
public static bool CheckCertificateRevocationList { get; set; }
member this.CheckCertificateRevocationList : bool with get, set

Returns
Boolean Boolean
true if the certificate revocation list is checked; otherwise, false .

Examples
The following code example sets this property.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;

Remarks
When the CheckCertificateRevocationList is true , the certificate is checked against the certificate authority revocation
list, as part of the certificate validation process. Its default value is false .
See ServicePointServicePoint
Also
ServicePointManager.ClientCipherSuitesCallback Service
PointManager.ClientCipherSuitesCallback
I n this Article
[System.Obsolete("This API is no longer supported.", true)]
public static System.Net.CipherSuitesCallback ClientCipherSuitesCallback { get; set; }
member this.ClientCipherSuitesCallback : System.Net.CipherSuitesCallback with get, set

Returns
CipherSuitesCallback CipherSuitesCallback
Attributes ObsoleteAttribute
ServicePointManager.DefaultConnectionLimit Service
PointManager.DefaultConnectionLimit
I n this Article
Gets or sets the maximum number of concurrent connections allowed by a ServicePoint object.

public static int DefaultConnectionLimit { get; set; }


member this.DefaultConnectionLimit : int with get, set

Returns
Int32 Int32
The maximum number of concurrent connections allowed by a ServicePoint object. The default connection limit is 10
for ASP.NET hosted applications and 2 for all others. When an app is running as an ASP.NET host, it is not possible to
alter the value of this property through the config file if the autoConfig property is set to true . However, you can
change the value programmatically when the autoConfig property is true . Set your preferred value once, when the
AppDomain loads.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
DefaultConnectionLimit is less than or equal to 0.

Examples
The following code example sets this property.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;

Remarks
The DefaultConnectionLimit property sets the default maximum number of concurrent connections that the
ServicePointManager object assigns to the ConnectionLimit property when creating ServicePoint objects.
Changing the DefaultConnectionLimit property has no effect on existing ServicePoint objects; it affects only
ServicePoint objects that are initialized after the change. If the value of this property has not been set either directly or
through configuration, the value defaults to the constant DefaultPersistentConnectionLimit.
Note

Any changes to the DefaultConnectionLimit property affect both HTTP 1.0 and HTTP 1.1 connections. It is not possible
to separately alter the connection limit for HTTP 1.0 and HTTP 1.1 protocols.
See ServicePointServicePoint
Also
ServicePointManager.DefaultNonPersistentConnection
Limit ServicePointManager.DefaultNonPersistent
ConnectionLimit
I n this Article
The default number of non-persistent connections (4) allowed on a ServicePoint object connected to an HTTP/1.0 or
later server. This field is constant but is no longer used in the .NET Framework 2.0.

public const int DefaultNonPersistentConnectionLimit = 4;


val mutable DefaultNonPersistentConnectionLimit : int

Returns
Int32 Int32
ServicePointManager.DefaultPersistentConnectionLimit
ServicePointManager.DefaultPersistentConnectionLimit
I n this Article
The default number of persistent connections (2) allowed on a ServicePoint object connected to an HTTP/1.1 or later
server. This field is constant and is used to initialize the DefaultConnectionLimit property if the value of the
DefaultConnectionLimit property has not been set either directly or through configuration.
public const int DefaultPersistentConnectionLimit = 2;
val mutable DefaultPersistentConnectionLimit : int

Returns
Int32 Int32

Examples
The following code example sets the DefaultConnectionLimit property using this field.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;
ServicePointManager.DnsRefreshTimeout ServicePoint
Manager.DnsRefreshTimeout
I n this Article
Gets or sets a value that indicates how long a Domain Name Service (DNS ) resolution is considered valid.

public static int DnsRefreshTimeout { get; set; }


member this.DnsRefreshTimeout : int with get, set

Returns
Int32 Int32
The time-out value, in milliseconds. A value of -1 indicates an infinite time-out period. The default value is 120,000
milliseconds (two minutes).

Examples
The following code example sets this property.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;
ServicePointManager.EnableDnsRoundRobin = true;
ServicePointManager.DnsRefreshTimeout = 4*60*1000; // 4 minutes

See ServicePointServicePoint
Also
ServicePointManager.EnableDnsRoundRobin Service
PointManager.EnableDnsRoundRobin
I n this Article
Gets or sets a value that indicates whether a Domain Name Service (DNS ) resolution rotates among the applicable
Internet Protocol (IP ) addresses.
public static bool EnableDnsRoundRobin { get; set; }
member this.EnableDnsRoundRobin : bool with get, set

Returns
Boolean Boolean
false if a DNS resolution always returns the first IP address for a particular host; otherwise true . The default is
false .

Examples
The following code example sets this property.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;
ServicePointManager.EnableDnsRoundRobin = true;
ServicePointManager.DnsRefreshTimeout = 4*60*1000; // 4 minutes

Remarks
When more than one IP address is associated with a host name, a DNS resolution normally returns only the first IP
address. If you set this property to true , then subsequent DNS resolutions will cycle through all available IP addresses
for a particular host. This option is useful when a service uses DNS as a load balancing mechanism between servers or
server clusters.
See ServicePointServicePoint
Also
ServicePointManager.EncryptionPolicy ServicePoint
Manager.EncryptionPolicy
I n this Article
Gets the EncryptionPolicy for this ServicePointManager instance.

public static System.Net.Security.EncryptionPolicy EncryptionPolicy { get; }


member this.EncryptionPolicy : System.Net.Security.EncryptionPolicy

Returns
EncryptionPolicy EncryptionPolicy
The encryption policy to use for this ServicePointManager instance.

Remarks
If a value is not specified in the configuration file, the EncryptionPolicy property defaults to
EncryptionPolicy.RequireEncryption. This is applied to an SSL/TLS session on this ServicePointManager instance.
The use of the Null cipher is required when the encryption policy is set to EncryptionPolicy.NoEncryption.
See ServicePointServicePoint
Also EncryptionPolicyEncryptionPolicy
ServicePointManager Element (Network Settings)
ServicePointManager.Expect100Continue ServicePoint
Manager.Expect100Continue
I n this Article
Gets or sets a Boolean value that determines whether 100-Continue behavior is used.

public static bool Expect100Continue { get; set; }


member this.Expect100Continue : bool with get, set

Returns
Boolean Boolean
true to enable 100-Continue behavior. The default value is true .

Examples
The following code example sets this property.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;

Remarks
When this property is set to true , 100-Continue behavior is used. Client requests that use the PUT and POST methods
will add an Expect header to the request if the Expect100Continue property is true and ContentLength property is
greater than zero or the SendChunked property is true. The client will expect to receive a 100-Continue response from
the server to indicate that the client should send the data to be posted. This mechanism allows clients to avoid sending
large amounts of data over the network when the server, based on the request headers, intends to reject the request.
For example, assume the Expect100Continue property is false . When the request is sent to the server, it includes the
data. If, after reading the request headers, the server requires authentication and must send a 401 response, the client
must resend the data with proper authentication headers.
If this property is true , the request headers are sent to the server. If the server has not rejected the request, it sends a
100-Continue response signaling that the data can be transmitted. If, as in the preceding example, the server requires
authentication, it sends the 401 response and the client has not unnecessarily transmitted the data.
Changing the value of this property does not affect existing ServicePoint objects. Only new ServicePoint objects
created after the change are affected.
The 100-Continue behavior is not used for HTTP 1.0 requests even if this property is set to true .
The Expect 100-Continue behavior is fully described in IETF RFC 2616 Section 10.1.1.
See ServicePointServicePoint
Also
ServicePointManager.FindServicePoint ServicePoint
Manager.FindServicePoint
I n this Article

Overloads
FindServicePoint(Uri, IWebProxy) FindServicePoint(Uri, IWeb
Proxy) Finds an existing ServicePoint object or creates a new
ServicePoint object to manage communications with the
specified Uri object.

FindServicePoint(Uri) FindServicePoint(Uri)
Finds an existing ServicePoint object or creates a new
ServicePoint object to manage communications with the
specified Uri object.

FindServicePoint(String, IWebProxy) FindServicePoint(String,


IWebProxy) Finds an existing ServicePoint object or creates a new
ServicePoint object to manage communications with the
specified Uniform Resource Identifier (URI).

FindServicePoint(Uri, IWebProxy) FindServicePoint(Uri,


IWebProxy)
Finds an existing ServicePoint object or creates a new ServicePoint object to manage communications with the
specified Uri object.

public static System.Net.ServicePoint FindServicePoint (Uri address, System.Net.IWebProxy proxy);


static member FindServicePoint : Uri * System.Net.IWebProxy -> System.Net.ServicePoint

Parameters
address Uri Uri
A Uri object that contains the address of the Internet resource to contact.
proxy IWebProxy IWebProxy
The proxy data for this request.
Returns
ServicePoint ServicePoint
The ServicePoint object that manages communications for the request.
Exceptions
ArgumentNullException ArgumentNullException
address is null .
InvalidOperationException InvalidOperationException
The maximum number of ServicePoint objects defined in MaxServicePoints has been reached.
Remarks
The FindServicePoint method returns the ServicePoint object associated with the specified Internet host name. If no
ServicePoint object exists for that host, the ServicePointManager object creates one.
See ServicePointServicePoint
Also

FindServicePoint(Uri) FindServicePoint(Uri)
Finds an existing ServicePoint object or creates a new ServicePoint object to manage communications with the
specified Uri object.
public static System.Net.ServicePoint FindServicePoint (Uri address);
static member FindServicePoint : Uri -> System.Net.ServicePoint

Parameters
address Uri Uri
The Uri object of the Internet resource to contact.
Returns
ServicePoint ServicePoint
The ServicePoint object that manages communications for the request.
Exceptions
ArgumentNullException ArgumentNullException
address is null .

InvalidOperationException InvalidOperationException
The maximum number of ServicePoint objects defined in MaxServicePoints has been reached.
Remarks
The FindServicePoint method returns the ServicePoint object associated with the specified Internet host name. If no
ServicePoint object exists for that host, the ServicePointManager object creates one.
See ServicePointServicePoint
Also

FindServicePoint(String, IWebProxy) FindServicePoint(String,


IWebProxy)
Finds an existing ServicePoint object or creates a new ServicePoint object to manage communications with the
specified Uniform Resource Identifier (URI).

public static System.Net.ServicePoint FindServicePoint (string uriString, System.Net.IWebProxy


proxy);
static member FindServicePoint : string * System.Net.IWebProxy -> System.Net.ServicePoint

Parameters
uriString String String
The URI of the Internet resource to be contacted.
proxy IWebProxy IWebProxy
The proxy data for this request.
Returns
ServicePoint ServicePoint
The ServicePoint object that manages communications for the request.
Exceptions
UriFormatException UriFormatException
The URI specified in uriString is invalid.
InvalidOperationException InvalidOperationException
The maximum number of ServicePoint objects defined in MaxServicePoints has been reached.
Examples
The following code example demonstrates calling this method to access a ServicePoint object.

public static void Main(string[] args)


{
int port = 80;

// Define a regular expression to parse the user's input.


// This is a security check. It allows only
// alphanumeric input strings between 2 to 40 characters long.
Regex rex = new Regex(@"^[a-zA-Z]\w{1,39}$");

if (args.Length < 1)
{
showUsage();
return;
}
string proxy = args[0];

if ((rex.Match(proxy)).Success != true)
{
Console.WriteLine("Input string format not allowed.");
return;
}
string proxyAdd = "http://" + proxy + ":" + port;

// Create a proxy object.


WebProxy DefaultProxy = new WebProxy(proxyAdd, true);

// Set the proxy that all HttpWebRequest instances use.


WebRequest.DefaultWebProxy = DefaultProxy;

// Get the base interface for proxy access for the


// WebRequest-based classes.
IWebProxy Iproxy = WebRequest.DefaultWebProxy;

// Set the maximum number of ServicePoint instances to


// maintain. If a ServicePoint instance for that host already
// exists when your application requests a connection to
// an Internet resource, the ServicePointManager object
// returns this existing ServicePoint instance. If none exists
// for that host, it creates a new ServicePoint instance.
ServicePointManager.MaxServicePoints = 4;
// Set the maximum idle time of a ServicePoint instance to 10 seconds.
// After the idle time expires, the ServicePoint object is eligible for
// garbage collection and cannot be used by the ServicePointManager object.
ServicePointManager.MaxServicePointIdleTime = 10000;

ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit =
ServicePointManager.DefaultPersistentConnectionLimit;
// Create the Uri object for the resource you want to access.
Uri MS = new Uri("http://msdn.microsoft.com/");

// Use the FindServicePoint method to find an existing


// ServicePoint object or to create a new one.
ServicePoint servicePoint = ServicePointManager.FindServicePoint(MS, Iproxy);

ShowProperties(servicePoint);

int hashCode = servicePoint.GetHashCode();

Console.WriteLine("Service point hashcode: " + hashCode);

// Make a request with the same scheme identifier and host fragment
// used to create the previous ServicePoint object.
makeWebRequest(hashCode, "http://msdn.microsoft.com/library/");
}

Remarks
The FindServicePoint method returns the ServicePoint object associated with the specified Internet host name. If no
ServicePoint object exists for that host, the ServicePointManager object creates one.
See UriUri
Also ServicePointServicePoint
ServicePointManager.MaxServicePointIdleTime Service
PointManager.MaxServicePointIdleTime
I n this Article
Gets or sets the maximum idle time of a ServicePoint object.

public static int MaxServicePointIdleTime { get; set; }


member this.MaxServicePointIdleTime : int with get, set

Returns
Int32 Int32
The maximum idle time, in milliseconds, of a ServicePoint object. The default value is 100,000 milliseconds (100
seconds).
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
MaxServicePointIdleTime is less than Infinite or greater than MaxValue.

Examples
The following code example sets this property.
// Set the maximum number of ServicePoint instances to
// maintain. If a ServicePoint instance for that host already
// exists when your application requests a connection to
// an Internet resource, the ServicePointManager object
// returns this existing ServicePoint instance. If none exists
// for that host, it creates a new ServicePoint instance.
ServicePointManager.MaxServicePoints = 4;

// Set the maximum idle time of a ServicePoint instance to 10 seconds.


// After the idle time expires, the ServicePoint object is eligible for
// garbage collection and cannot be used by the ServicePointManager object.
ServicePointManager.MaxServicePointIdleTime = 10000;

Remarks
The MaxServicePointIdleTime property sets the maximum idle time that the ServicePointManager object assigns to the
MaxIdleTime property when creating ServicePoint objects. Changes to this value affect only ServicePoint objects that
are initialized after the value is changed.
After a ServicePoint object has been idle for the time specified in MaxIdleTime, it is eligible for garbage collection. A
ServicePoint object is idle when the list of connections associated with the ServicePoint object is empty.
See ServicePointServicePoint
Also
ServicePointManager.MaxServicePoints ServicePoint
Manager.MaxServicePoints
I n this Article
Gets or sets the maximum number of ServicePoint objects to maintain at any time.

public static int MaxServicePoints { get; set; }


member this.MaxServicePoints : int with get, set

Returns
Int32 Int32
The maximum number of ServicePoint objects to maintain. The default value is 0, which means there is no limit to the
number of ServicePoint objects.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
MaxServicePoints is less than 0 or greater than MaxValue.

Examples
The following code example sets this property.
// Set the maximum number of ServicePoint instances to
// maintain. If a ServicePoint instance for that host already
// exists when your application requests a connection to
// an Internet resource, the ServicePointManager object
// returns this existing ServicePoint instance. If none exists
// for that host, it creates a new ServicePoint instance.
ServicePointManager.MaxServicePoints = 4;

// Set the maximum idle time of a ServicePoint instance to 10 seconds.


// After the idle time expires, the ServicePoint object is eligible for
// garbage collection and cannot be used by the ServicePointManager object.
ServicePointManager.MaxServicePointIdleTime = 10000;

Remarks
When you reduce the MaxServicePoints property below the number of ServicePoint objects currently in existence, the
ServicePointManager deletes the ServicePoint objects with the longest idle times. If the number of ServicePoint objects
with active connections is greater than the value of MaxServicePoints, the ServicePointManager object deletes the
ServicePoint objects as they become idle.
See ServicePointServicePoint
Also
ServicePointManager.ReusePort ServicePointManager.
ReusePort
I n this Article
Setting this property value to true causes all outbound TCP connections from HttpWebRequest to use the native
socket option SO_REUSE_UNICASTPORT on the socket. This causes the underlying outgoing ports to be shared. This
is useful for scenarios where a large number of outgoing connections are made in a short time, and the app risks
running out of ports.
public static bool ReusePort { get; set; }
member this.ReusePort : bool with get, set

Returns
Boolean Boolean
Returns Boolean.

Remarks
The default value is false .
ServicePointManager.SecurityProtocol ServicePoint
Manager.SecurityProtocol
I n this Article
Gets or sets the security protocol used by the ServicePoint objects managed by the ServicePointManager object.

public static System.Net.SecurityProtocolType SecurityProtocol { get; set; }


member this.SecurityProtocol : System.Net.SecurityProtocolType with get, set

Returns
SecurityProtocolType SecurityProtocolType
One of the values defined in the SecurityProtocolType enumeration.
Exceptions
NotSupportedException NotSupportedException
The value specified to set the property is not a valid SecurityProtocolType enumeration value.

Remarks
This property selects the version of the Secure Sockets Layer (SSL ) or Transport Layer Security (TLS ) protocol to use
for new connections; existing connections aren't changed.
Starting with the .NET Framework 4.7, the default value of this property is SecurityProtocolType.SystemDefault. This
allows .NET Framework networking APIs based on SslStream (such as FTP, HTTP, and SMTP ) to inherit the default
security protocols from the operating system or from any custom configurations performed by a system administrator.
For information about which SSL/TLS protocols are enabled by default on each version of the Windows operating
system, see Protocols in TLS/SSL (Schannel SSP ).
For versions of the .NET Framework through the .NET Framework 4.6.2, no default value is listed for this property. The
security landscape changes constantly, and default protocols and protection levels are changed over time in order to
avoid known weaknesses. Defaults vary depending on individual machine configuration, installed software, and applied
patches.
Your code should never implicitly depend on using a particular protection level, or on the assumption that a given
security level is used by default. If your app depends on the use of a particular security level, you must explicitly specify
that level and then check to be sure that it is actually in use on the established connection. Further, your code should be
designed to be robust in the face of changes to which protocols are supported, as such changes are often made with
little advance notice in order to mitigate emerging threats.
The .NET Framework 4.6 includes a new security feature that blocks insecure cipher and hashing algorithms for
connections. Applications using TLS/SSL through APIs such as HttpClient, HttpWebRequest, FTPClient, SmtpClient,
SslStream, etc. and targeting .NET Framework 4.6 get the more-secure behavior by default.
Developers may want to opt out of this behavior in order to maintain interoperability with their existing SSL3 services
OR TLS w/ RC4 services. This article explains how to modify your code so that the new behavior is disabled.
See ServicePointServicePoint
Also SecurityProtocolTypeSecurityProtocolType
ServicePointManager.ServerCertificateValidationCallback
ServicePointManager.ServerCertificateValidationCallback
I n this Article
Gets or sets the callback to validate a server certificate.

public static System.Net.Security.RemoteCertificateValidationCallback


ServerCertificateValidationCallback { get; set; }
member this.ServerCertificateValidationCallback :
System.Net.Security.RemoteCertificateValidationCallback with get, set

Returns
RemoteCertificateValidationCallback RemoteCertificateValidationCallback
A RemoteCertificateValidationCallback. The default value is null .

Remarks
An application can set the ServerCertificateValidationCallback property to a method to use for custom validation by the
client of the server certificate. When doing custom validation, the sender parameter passed to the
RemoteCertificateValidationCallback can be a host string name or an object derived from WebRequest
(HttpWebRequest, for example) depending on the CertificatePolicy property.

When custom validation is not used, the certificate name is compared with the host name used to create the request.
For example, if Create(String) was passed a parameter of "https://www.contoso.com/default.html" , the default
behavior is for the client to check the certificate against www.contoso.com .
Despite being a multicast delegate, only the value returned from the last-executed event handler is considered
authoritative. In other words, you can attach multiple delegates, and they all get a callback from
ServerCertificateValidationCallback. Each callback returns a value that indicates whether the certificate is accepted or
not; however, only the value from the last delegate is respected.
See ServicePointServicePoint
Also
ServicePointManager.ServerCipherSuitesCallback Service
PointManager.ServerCipherSuitesCallback
I n this Article
[System.Obsolete("This API is no longer supported.", true)]
public static System.Net.CipherSuitesCallback ServerCipherSuitesCallback { get; set; }
member this.ServerCipherSuitesCallback : System.Net.CipherSuitesCallback with get, set

Returns
CipherSuitesCallback CipherSuitesCallback
Attributes ObsoleteAttribute
ServicePointManager.SetTcpKeepAlive ServicePoint
Manager.SetTcpKeepAlive
I n this Article
Enables or disables the keep-alive option on a TCP connection.

public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval);
static member SetTcpKeepAlive : bool * int * int -> unit

Parameters
enabled Boolean Boolean
If set to true, then the TCP keep-alive option on a TCP connection will be enabled using the specified keepAliveTime
and keepAliveInterval values.
If set to false, then the TCP keep-alive option is disabled and the remaining parameters are ignored.
The default value is false.
keepAliveTime Int32 Int32
Specifies the timeout, in milliseconds, with no activity until the first keep-alive packet is sent.
The value must be greater than 0. If a value of less than or equal to zero is passed an ArgumentOutOfRangeException
is thrown.
keepAliveInterval Int32 Int32
Specifies the interval, in milliseconds, between when successive keep-alive packets are sent if no acknowledgement is
received.
The value must be greater than 0. If a value of less than or equal to zero is passed an ArgumentOutOfRangeException
is thrown.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The value specified for keepAliveTime or keepAliveInterval parameter is less than or equal to 0.

Remarks
An application can request that a TCP/IP provider enable the use of keep-alive packets on a TCP connection. The
default is that the use of keep-alive packets on a TCP connection is disabled.
The default settings when a TCP socket is initialized sets the keep-alive timeout to 2 hours and the keep-alive interval
to 1 second. The keepAliveTime parameter specifies the timeout, in milliseconds, with no activity until the first keep-
alive packet is sent. The keepAliveInterval parameter specifies the interval, in milliseconds, between when successive
keep-alive packets are sent if no acknowledgement is received. The number of keep-alive probes cannot be changed
and is set to 10.
If a TCP connection is dropped as the result of keep-alives, a SocketError of NetworkReset is returned to any calls in
progress on the socket, and any subsequent calls will fail with a SocketError of NotConnected.
See ServicePointServicePoint
Also
ServicePointManager.UseNagleAlgorithm ServicePoint
Manager.UseNagleAlgorithm
I n this Article
Determines whether the Nagle algorithm is used by the service points managed by this ServicePointManager object.

public static bool UseNagleAlgorithm { get; set; }


member this.UseNagleAlgorithm : bool with get, set

Returns
Boolean Boolean
true to use the Nagle algorithm; otherwise, false . The default value is true .

Examples
The following code example sets this property.
ServicePointManager.UseNagleAlgorithm = true;
ServicePointManager.Expect100Continue = true;
ServicePointManager.CheckCertificateRevocationList = true;
ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit;

Remarks
The Nagle algorithm is used to reduce network traffic by buffering small packets of data and transmitting them as a
single packet. This process is also referred to as "nagling"; it is widely used because it reduces the number of packets
transmitted and lowers the overhead per packet.
Changing the value of this property does not affect existing ServicePoint objects. Only new service points created after
the change are affected.
The Nagle algorithm is fully described in IETF RFC 896.
See ServicePointServicePoint
Also
SocketAddress SocketAddress Class
Stores serialized information from EndPoint derived classes.

D eclaration
public class SocketAddress
type SocketAddress = class

I nheritance H ierarchy
Object Object

Remarks
The first 2 bytes of the underlying buffer are reserved for the AddressFamily enumerated value. When the
SocketAddress is used to store a serialized IPEndPoint, the third and fourth bytes are used to store port number
information. The next bytes are used to store the IP address. You can access any information within this underlying
byte buffer by referring to its index position; the byte buffer uses zero-based indexing. You can also use the Family and
Size properties to get the AddressFamily value and the buffer size, respectively. To view any of this information as a
string, use the ToString method.

Constructors
SocketAddress(AddressFamily)
SocketAddress(AddressFamily)

Creates a new instance of the SocketAddress class for the given address family.

SocketAddress(AddressFamily, Int32)
SocketAddress(AddressFamily, Int32)

Creates a new instance of the SocketAddress class using the specified address family and buffer size.

Properties
Family
Family

Gets the AddressFamily enumerated value of the current SocketAddress.

Item[Int32]
Item[Int32]

Gets or sets the specified index element in the underlying buffer.

Size
Size
Gets the underlying buffer size of the SocketAddress.

Methods
Equals(Object)
Equals(Object)

Determines whether the specified Object is equal to the current Object .

GetHashCode()
GetHashCode()

Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a
hash table.

ToString()
ToString()

Returns information about the socket address.


SocketAddress.Equals SocketAddress.Equals
I n this Article
Determines whether the specified Object is equal to the current Object .

public override bool Equals (object comparand);


override this.Equals : obj -> bool

Parameters
comparand Object Object
The Object to compare with the current Object .
Returns
Boolean Boolean
true if the specified Object is equal to the current Object ; otherwise, false .
SocketAddress.Family SocketAddress.Family
I n this Article
Gets the AddressFamily enumerated value of the current SocketAddress.
public System.Net.Sockets.AddressFamily Family { get; }
member this.Family : System.Net.Sockets.AddressFamily

Returns
AddressFamily AddressFamily
One of the AddressFamily enumerated values.

Remarks
This method gets the AddressFamily enumerated value that represents the addressing scheme of the current
SocketAddress. If you want to view the corresponding string representation of AddressFamily, use the ToString
method.
See AddressFamilyAddressFamily
Also
SocketAddress.GetHashCode SocketAddress.GetHash
Code
I n this Article
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash
table.
public override int GetHashCode ();
override this.GetHashCode : unit -> int

Returns
Int32 Int32
A hash code for the current Object.
SocketAddress.Item[Int32] SocketAddress.Item[Int32]
I n this Article
Gets or sets the specified index element in the underlying buffer.
public byte this[int offset] { get; set; }
member this.Item(int) : byte with get, set

Parameters
offset Int32 Int32
The array index element of the desired information.
Returns
Byte Byte
The value of the specified index element in the underlying buffer.
Exceptions
IndexOutOfRangeException IndexOutOfRangeException
The specified index does not exist in the buffer.

Remarks
This property gets or sets the specified byte position in the underlying buffer.
Note

Be sure to call Size before referring to elements in the underlying buffer. Referring to an index that does not exist will
cause the SocketAddress to throw an IndexOutOfRangeException.
See SizeSize
Also
SocketAddress.Size SocketAddress.Size
I n this Article
Gets the underlying buffer size of the SocketAddress.
public int Size { get; }
member this.Size : int

Returns
Int32 Int32
The underlying buffer size of the SocketAddress.

Remarks
This property gets the underlying buffer size of the SocketAddress in bytes.
SocketAddress SocketAddress
I n this Article

Overloads
SocketAddress(AddressFamily) SocketAddress(AddressFamily)
Creates a new instance of the SocketAddress class for the
given address family.

SocketAddress(AddressFamily, Int32) SocketAddress(Address


Family, Int32) Creates a new instance of the SocketAddress class using the
specified address family and buffer size.

SocketAddress(AddressFamily) SocketAddress(AddressFamily)
Creates a new instance of the SocketAddress class for the given address family.
public SocketAddress (System.Net.Sockets.AddressFamily family);
new System.Net.SocketAddress : System.Net.Sockets.AddressFamily -> System.Net.SocketAddress

Parameters
family AddressFamily AddressFamily
An AddressFamily enumerated value.
Remarks
This overload sets the underlying buffer size to 32 bytes.

SocketAddress(AddressFamily, Int32)
SocketAddress(AddressFamily, Int32)
Creates a new instance of the SocketAddress class using the specified address family and buffer size.
public SocketAddress (System.Net.Sockets.AddressFamily family, int size);
new System.Net.SocketAddress : System.Net.Sockets.AddressFamily * int -> System.Net.SocketAddress

Parameters
family AddressFamily AddressFamily
An AddressFamily enumerated value.
size Int32 Int32
The number of bytes to allocate for the underlying buffer.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
size is less than 2. These 2 bytes are needed to store family .
Remarks
Use this overload to create a new instance of the SocketAddress class with a particular underlying buffer size.
SocketAddress.ToString SocketAddress.ToString
I n this Article
Returns information about the socket address.
public override string ToString ();
override this.ToString : unit -> string

Returns
String String
A string that contains information about the SocketAddress.

Remarks
The ToString method returns a string that contains the AddressFamily enumerated value, the size of the underlying
buffer of the SocketAddress structure, and the remaining contents of the buffer.
SocketPermission SocketPermission Class
Controls rights to make or accept connections on a transport address.

D eclaration
[System.Serializable]
public sealed class SocketPermission : System.Security.CodeAccessPermission,
System.Security.Permissions.IUnrestrictedPermission
type SocketPermission = class
inherit CodeAccessPermission
interface IUnrestrictedPermission

I nheritance H ierarchy
Object Object
CodeAccessPermission CodeAccessPermission

Remarks
SocketPermission instances control permission to accept connections or initiate Socket connections. A Socket
permission can be established for a host name or IP address, a port number, and a transport protocol.
Note

Avoid creating socket permissions using host names, as these names have to be resolved to IP addresses, and this
might block the stack.

Constructors
SocketPermission(PermissionState)
SocketPermission(PermissionState)

Initializes a new instance of the SocketPermission class that allows unrestricted access to the Socket or disallows
access to the Socket.

SocketPermission(NetworkAccess, TransportType, String, Int32)


SocketPermission(NetworkAccess, TransportType, String, Int32)

Initializes a new instance of the SocketPermission class for the given transport address with the specified
permission.

Fields
AllPorts
AllPorts

Defines a constant that represents all ports.

Properties
AcceptList
AcceptList

Gets a list of EndpointPermission instances that identifies the endpoints that can be accepted under this
permission instance.

ConnectList
ConnectList

Gets a list of EndpointPermission instances that identifies the endpoints that can be connected to under this
permission instance.

Methods
AddPermission(NetworkAccess, TransportType, String, Int32)
AddPermission(NetworkAccess, TransportType, String, Int32)

Adds a permission to the set of permissions for a transport address.

Copy()
Copy()

Creates a copy of a SocketPermission instance.

FromXml(SecurityElement)
FromXml(SecurityElement)

Reconstructs a SocketPermission instance for an XML encoding.

Intersect(IPermission)
Intersect(IPermission)

Returns the logical intersection between two SocketPermission instances.

IsSubsetOf(IPermission)
IsSubsetOf(IPermission)

Determines if the current permission is a subset of the specified permission.

IsUnrestricted()
IsUnrestricted()

Checks the overall permission state of the object.

ToXml()
ToXml()
Creates an XML encoding of a SocketPermission instance and its current state.

Union(IPermission)
Union(IPermission)

Returns the logical union between two SocketPermission instances.


SocketPermission.AcceptList SocketPermission.AcceptList
I n this Article
Gets a list of EndpointPermission instances that identifies the endpoints that can be accepted under this permission
instance.

public System.Collections.IEnumerator AcceptList { get; }


member this.AcceptList : System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
An instance that implements the IEnumerator interface that contains EndpointPermission instances.

Examples
The following example uses the AcceptList property to return a list of endpoints to which accept privileges are granted.

// Creates a SocketPermission restricting access to and from all URIs.


SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

// The socket to which this permission will apply will allow connections from www.contoso.com.
mySocketPermission1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.contoso.com",
11000);

// Creates a SocketPermission which will allow the target Socket to connect with
www.southridgevideo.com.
SocketPermission mySocketPermission2 =
new SocketPermission(NetworkAccess.Connect, TransportType.Tcp,
"www.southridgevideo.com", 11002);

// Creates a SocketPermission from the union of two SocketPermissions.


SocketPermission mySocketPermissionUnion =
(SocketPermission)mySocketPermission1.Union(mySocketPermission2);

// Checks to see if the union was successfully created by using the IsSubsetOf method.
if (mySocketPermission1.IsSubsetOf(mySocketPermissionUnion) &&
mySocketPermission2.IsSubsetOf(mySocketPermissionUnion)){
Console.WriteLine("This union contains permissions from both mySocketPermission1 and
mySocketPermission2");

// Prints the allowable accept URIs to the console.


Console.WriteLine("This union accepts connections on :");

IEnumerator myEnumerator = mySocketPermissionUnion.AcceptList;


while (myEnumerator.MoveNext()) {
Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
}

// Prints the allowable connect URIs to the console.


Console.WriteLine("This union permits connections to :");

myEnumerator = mySocketPermissionUnion.ConnectList;
while (myEnumerator.MoveNext()) {
Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
}

}
SocketPermission.AddPermission SocketPermission.Add
Permission
I n this Article
Adds a permission to the set of permissions for a transport address.

public void AddPermission (System.Net.NetworkAccess access, System.Net.TransportType transport,


string hostName, int portNumber);
member this.AddPermission : System.Net.NetworkAccess * System.Net.TransportType * string * int ->
unit

Parameters
access NetworkAccess NetworkAccess
One of the NetworkAccess values.
transport TransportType TransportType
One of the TransportType values.
hostName String String
The host name for the transport address.
portNumber Int32 Int32
The port number for the transport address.
Exceptions
ArgumentNullException ArgumentNullException
hostName is null .

Examples
The following example uses the AddPermission method to add connection permissions to the specified host.
SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement1 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
// for 'All'ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
// for 'All' ports for the ip-address.
SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement2.AddChild(securityElement3);
securityElement2.AddChild(securityElement4);
securityElement1.AddChild(securityElement2);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement1);

Console.WriteLine("
Displays the result of FromXml method :
");
Console.WriteLine(socketPermission2.ToString());

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All'
ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("Displays the result of AddPermission method :


");
Console.WriteLine(socketPermission3.ToString());

// Find the intersection between two 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

Console.WriteLine("Displays the result of Intersect method :


");
Console.WriteLine(socketPermission1.ToString());

// Demand that the calling method have the requsite socket permission.
socketPermission1.Demand();

Remarks
The hostName can be a DNS name, an IP address, or a specified IP subnet, such as 192.168.1.*.
SocketPermission.AllPorts SocketPermission.AllPorts
I n this Article
Defines a constant that represents all ports.
public const int AllPorts = -1;
val mutable AllPorts : int

Returns
Int32 Int32

Examples
The following example uses the AllPorts property to provide connection permissions to all of the resources ports.
SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement1 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
// for 'All'ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
// for 'All' ports for the ip-address.
SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement2.AddChild(securityElement3);
securityElement2.AddChild(securityElement4);
securityElement1.AddChild(securityElement2);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement1);

Console.WriteLine("\nDisplays the result of FromXml method : \n");


Console.WriteLine(socketPermission2.ToString());

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All'
ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("Displays the result of AddPermission method : \n");


Console.WriteLine(socketPermission3.ToString());

// Find the intersection between two 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

Console.WriteLine("Displays the result of Intersect method :\n ");


Console.WriteLine(socketPermission1.ToString());

// Demand that the calling method have the requsite socket permission.
socketPermission1.Demand();

Remarks
This field is read-only. The value of this field is -1.
SocketPermission.ConnectList SocketPermission.Connect
List
I n this Article
Gets a list of EndpointPermission instances that identifies the endpoints that can be connected to under this permission
instance.
public System.Collections.IEnumerator ConnectList { get; }
member this.ConnectList : System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
An instance that implements the IEnumerator interface that contains EndpointPermission instances.

Examples
The following example uses the ConnectList property to return a list of endpoints to which connection privileges are
granted.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Security;
using System.Security.Permissions;

public class DateClient {

private Socket serverSocket;


private Encoding asciiEncoding;
private IPAddress serverAddress;

private int serverPort;

// The constructor takes the address and port of the remote server.
public DateClient(IPAddress serverIpAddress, int port) {
serverAddress = serverIpAddress;
serverPort = port;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
asciiEncoding = Encoding.ASCII;
}

// Print a security element and all its children, in a depth-first manner.


private void PrintSecurityElement(SecurityElement securityElementObj, int depth) {

Console.WriteLine("Depth : {0}", depth);


Console.WriteLine("Tag : {0}", securityElementObj.Tag);
Console.WriteLine("Text : {0}", securityElementObj.Text);
if(securityElementObj.Children != null)
Console.WriteLine("Children : {0}", securityElementObj.Children.Count);

if(securityElementObj.Attributes != null) {
IEnumerator attributeEnumerator = securityElementObj.Attributes.GetEnumerator();
while(attributeEnumerator.MoveNext())
Console.WriteLine("Attribute - \"{0}\" , Value - \"{1}\"",
((IDictionaryEnumerator)attributeEnumerator).Key,
((IDictionaryEnumerator)attributeEnumerator).Value);
}
}

Console.WriteLine("");

if(securityElementObj.Children != null) {
depth += 1;
for(int i = 0; i < securityElementObj.Children.Count; i++)
PrintSecurityElement((SecurityElement)(securityElementObj.Children[i]), depth);
}
}

public String GetDate()


{

SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement4 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement1 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for
'All' ports for the ip-address.
SecurityElement securityElement2 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and for
'All' ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement1.AddChild(securityElement2);
securityElement1.AddChild(securityElement3);
securityElement4.AddChild(securityElement1);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement4);

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for
'All' ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("
Checks the Socket permissions using IsUnrestricted method : ");
if(socketPermission1.IsUnrestricted())
Console.WriteLine("Socket permission is unrestricted");
else
Console.WriteLine("Socket permission is restricted");

Console.WriteLine();

Console.WriteLine("Display result of ConnectList property :


");
IEnumerator enumerator = socketPermission3.ConnectList;
while(enumerator.MoveNext()) {
Console.WriteLine("The hostname is : {0}",
((EndpointPermission)enumerator.Current).Hostname);
Console.WriteLine("The port is : {0}", ((EndpointPermission)enumerator.Current).Port);
Console.WriteLine("The Transport type is : {0}",
((EndpointPermission)enumerator.Current).Transport);
}
Console.WriteLine("");

Console.WriteLine("Display Security Elements :


");
PrintSecurityElement(socketPermission2.ToXml(), 0);

// Get a 'SocketPermission' object which is a union of two other 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission3.Union(socketPermission2);

// Demand that the calling method have the socket permission.


socketPermission1.Demand();

// Get the current date from the remote date server.


try {
int bytesReceived;
byte[] getByte = new byte[100];
serverSocket.Connect(new IPEndPoint( serverAddress, serverPort));
bytesReceived = serverSocket.Receive( getByte, getByte.Length, 0 );
return asciiEncoding.GetString( getByte, 0, bytesReceived );
}
catch(Exception e)
{
Console.WriteLine("
Exception raised : {0}", e.Message);
return "";
}
}
};
SocketPermission.Copy SocketPermission.Copy
I n this Article
Creates a copy of a SocketPermission instance.
public override System.Security.IPermission Copy ();
override this.Copy : unit -> System.Security.IPermission

Returns
IPermission IPermission
A new instance of the SocketPermission class that is a copy of the current instance.

Examples
The following example creates a SocketPermission by taking a copy of an existing SocketPermission.
// Creates a copy of the intersect SocketPermission.
SocketPermission mySocketPermissionIntersectCopy =
(SocketPermission)mySocketPermissionIntersect.Copy();

if (mySocketPermissionIntersectCopy.Equals(mySocketPermissionIntersect)){
Console.WriteLine("Copy successfull");
}

Remarks
The object returned by this method represents the same level of access as the current instance. This method overrides
Copy and is implemented to support the IPermission interface.
SocketPermission.FromXml SocketPermission.FromXml
I n this Article
Reconstructs a SocketPermission instance for an XML encoding.
public override void FromXml (System.Security.SecurityElement securityElement);
override this.FromXml : System.Security.SecurityElement -> unit

Parameters
securityElement SecurityElement SecurityElement
The XML encoding used to reconstruct the SocketPermission instance.
Exceptions
ArgumentNullException ArgumentNullException
The securityElement is null .
ArgumentException ArgumentException
The securityElement is not a permission element for this type.

Examples
The following example uses the FromXml method to convert XML encoded data to a SocketPermission instance.
SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement1 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
// for 'All'ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
// for 'All' ports for the ip-address.
SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement2.AddChild(securityElement3);
securityElement2.AddChild(securityElement4);
securityElement1.AddChild(securityElement2);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement1);

Console.WriteLine("
Displays the result of FromXml method :
");
Console.WriteLine(socketPermission2.ToString());

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All'
ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("Displays the result of AddPermission method :


");
Console.WriteLine(socketPermission3.ToString());

// Find the intersection between two 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

Console.WriteLine("Displays the result of Intersect method :


");
Console.WriteLine(socketPermission1.ToString());

// Demand that the calling method have the requsite socket permission.
socketPermission1.Demand();

Remarks
The FromXml method reconstructs a SocketPermission instance from an XML encoding defined by the
SecurityElement class.
Use the ToXml method to encode the SocketPermission instance, including state information, in XML.
SocketPermission.Intersect SocketPermission.Intersect
I n this Article
Returns the logical intersection between two SocketPermission instances.
public override System.Security.IPermission Intersect (System.Security.IPermission target);
override this.Intersect : System.Security.IPermission -> System.Security.IPermission

Parameters
target IPermission IPermission
The SocketPermission instance to intersect with the current instance.
Returns
IPermission IPermission
The SocketPermission instance that represents the intersection of two SocketPermission instances. If the intersection is
empty, the method returns null . If the target parameter is a null reference, the method returns null .
Exceptions
ArgumentException ArgumentException
The target parameter is not a SocketPermission.
SecurityException SecurityException
DnsPermission is not granted to the method caller.

Examples
The following example uses the Intersect method to obtain a logical intersection between two SocketPermission
instances.
SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement1 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
// for 'All'ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
// for 'All' ports for the ip-address.
SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement2.AddChild(securityElement3);
securityElement2.AddChild(securityElement4);
securityElement1.AddChild(securityElement2);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement1);

Console.WriteLine("
Displays the result of FromXml method :
");
Console.WriteLine(socketPermission2.ToString());

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All'
ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("Displays the result of AddPermission method :


");
Console.WriteLine(socketPermission3.ToString());

// Find the intersection between two 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

Console.WriteLine("Displays the result of Intersect method :


");
Console.WriteLine(socketPermission1.ToString());

// Demand that the calling method have the requsite socket permission.
socketPermission1.Demand();

Remarks
The intersection of two permissions is a permission that helps to protect the resources and operations protected by
both permissions. Specifically, it represents the minimum permission such that any demand that passes both
permissions also passes their intersection. This method overrides Intersect and is implemented to support the
IPermission interface.
SocketPermission.IsSubsetOf SocketPermission.IsSubset
Of
I n this Article
Determines if the current permission is a subset of the specified permission.

public override bool IsSubsetOf (System.Security.IPermission target);


override this.IsSubsetOf : System.Security.IPermission -> bool

Parameters
target IPermission IPermission
A SocketPermission that is to be tested for the subset relationship.
Returns
Boolean Boolean
If target is null , this method returns true if the current instance defines no permissions; otherwise, false . If
target is not null , this method returns true if the current instance defines a subset of target permissions;
otherwise, false .
Exceptions
ArgumentException ArgumentException
target is not a SocketException.
SecurityException SecurityException
DnsPermission is not granted to the method caller.

Examples
The following example uses the IsSubsetOf method to determine if one SocketPermission is the subset of another.
// Creates a SocketPermission restricting access to and from all URIs.
SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

// The socket to which this permission will apply will allow connections from www.contoso.com.
mySocketPermission1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.contoso.com",
11000);

// Creates a SocketPermission which will allow the target Socket to connect with
www.southridgevideo.com.
SocketPermission mySocketPermission2 =
new SocketPermission(NetworkAccess.Connect, TransportType.Tcp,
"www.southridgevideo.com", 11002);

// Creates a SocketPermission from the union of two SocketPermissions.


SocketPermission mySocketPermissionUnion =
(SocketPermission)mySocketPermission1.Union(mySocketPermission2);

// Checks to see if the union was successfully created by using the IsSubsetOf method.
if (mySocketPermission1.IsSubsetOf(mySocketPermissionUnion) &&
mySocketPermission2.IsSubsetOf(mySocketPermissionUnion)){
Console.WriteLine("This union contains permissions from both mySocketPermission1 and
mySocketPermission2");

// Prints the allowable accept URIs to the console.


Console.WriteLine("This union accepts connections on :");

IEnumerator myEnumerator = mySocketPermissionUnion.AcceptList;


while (myEnumerator.MoveNext()) {
Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
}

// Prints the allowable connect URIs to the console.


Console.WriteLine("This union permits connections to :");

myEnumerator = mySocketPermissionUnion.ConnectList;
while (myEnumerator.MoveNext()) {
Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
}

Remarks
The current permission is a subset of the specified permission if the current permission specifies a set of operations
that is wholly contained by the specified permission.
For example, a permission that represents access to 192.168.1.1:80 is a subset of a permission that represents access to
192.168.1.1:Any. If this method returns true , the current permission represents no more access to the protected
resource than does the specified permission.
SocketPermission.IsUnrestricted SocketPermission.Is
Unrestricted
I n this Article
Checks the overall permission state of the object.

public bool IsUnrestricted ();


override this.IsUnrestricted : unit -> bool

Returns
Boolean Boolean
true if the SocketPermission instance is created with the Unrestricted value from PermissionState; otherwise,
false .

Examples
The following example checks the IsUnrestricted property to determine if the specified SocketPermission has any
restrictions.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Security;
using System.Security.Permissions;

public class DateClient {

private Socket serverSocket;


private Encoding asciiEncoding;
private IPAddress serverAddress;

private int serverPort;

// The constructor takes the address and port of the remote server.
public DateClient(IPAddress serverIpAddress, int port) {
serverAddress = serverIpAddress;
serverPort = port;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
asciiEncoding = Encoding.ASCII;
}

// Print a security element and all its children, in a depth-first manner.


private void PrintSecurityElement(SecurityElement securityElementObj, int depth) {

Console.WriteLine("Depth : {0}", depth);


Console.WriteLine("Tag : {0}", securityElementObj.Tag);
Console.WriteLine("Text : {0}", securityElementObj.Text);
if(securityElementObj.Children != null)
Console.WriteLine("Children : {0}", securityElementObj.Children.Count);

if(securityElementObj.Attributes != null) {
IEnumerator attributeEnumerator = securityElementObj.Attributes.GetEnumerator();
while(attributeEnumerator.MoveNext())
Console.WriteLine("Attribute - \"{0}\" , Value - \"{1}\"",
((IDictionaryEnumerator)attributeEnumerator).Key,
((IDictionaryEnumerator)attributeEnumerator).Value);
}
}

Console.WriteLine("");

if(securityElementObj.Children != null) {
depth += 1;
for(int i = 0; i < securityElementObj.Children.Count; i++)
PrintSecurityElement((SecurityElement)(securityElementObj.Children[i]), depth);
}
}

public String GetDate()


{

SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement4 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement1 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for
'All' ports for the ip-address.
SecurityElement securityElement2 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and for
'All' ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement1.AddChild(securityElement2);
securityElement1.AddChild(securityElement3);
securityElement4.AddChild(securityElement1);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement4);

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for
'All' ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("
Checks the Socket permissions using IsUnrestricted method : ");
if(socketPermission1.IsUnrestricted())
Console.WriteLine("Socket permission is unrestricted");
else
Console.WriteLine("Socket permission is restricted");

Console.WriteLine();

Console.WriteLine("Display result of ConnectList property :


");
IEnumerator enumerator = socketPermission3.ConnectList;
while(enumerator.MoveNext()) {
Console.WriteLine("The hostname is : {0}",
((EndpointPermission)enumerator.Current).Hostname);
((EndpointPermission)enumerator.Current).Hostname);
Console.WriteLine("The port is : {0}", ((EndpointPermission)enumerator.Current).Port);
Console.WriteLine("The Transport type is : {0}",
((EndpointPermission)enumerator.Current).Transport);
}
Console.WriteLine("");

Console.WriteLine("Display Security Elements :


");
PrintSecurityElement(socketPermission2.ToXml(), 0);

// Get a 'SocketPermission' object which is a union of two other 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission3.Union(socketPermission2);

// Demand that the calling method have the socket permission.


socketPermission1.Demand();

// Get the current date from the remote date server.


try {
int bytesReceived;
byte[] getByte = new byte[100];
serverSocket.Connect(new IPEndPoint( serverAddress, serverPort));
bytesReceived = serverSocket.Receive( getByte, getByte.Length, 0 );
return asciiEncoding.GetString( getByte, 0, bytesReceived );
}
catch(Exception e)
{
Console.WriteLine("
Exception raised : {0}", e.Message);
return "";
}
}
};
SocketPermission SocketPermission
I n this Article

Overloads
SocketPermission(PermissionState) SocketPermission(
PermissionState) Initializes a new instance of the SocketPermission class that
allows unrestricted access to the Socket or disallows access to
the Socket.

SocketPermission(NetworkAccess, TransportType, String, Int32)


SocketPermission(NetworkAccess, TransportType, String, Int32) Initializes a new instance of the SocketPermission class for the
given transport address with the specified permission.

SocketPermission(PermissionState)
SocketPermission(PermissionState)
Initializes a new instance of the SocketPermission class that allows unrestricted access to the Socket or disallows access
to the Socket.
public SocketPermission (System.Security.Permissions.PermissionState state);
new System.Net.SocketPermission : System.Security.Permissions.PermissionState ->
System.Net.SocketPermission

Parameters
state PermissionState PermissionState
One of the PermissionState values.
Examples
The following example creates a SocketPermission using a PermissionState enumerated value.
SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement1 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
// for 'All'ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
// for 'All' ports for the ip-address.
SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement2.AddChild(securityElement3);
securityElement2.AddChild(securityElement4);
securityElement1.AddChild(securityElement2);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement1);

Console.WriteLine("
Displays the result of FromXml method :
");
Console.WriteLine(socketPermission2.ToString());

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All'
ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("Displays the result of AddPermission method :


");
Console.WriteLine(socketPermission3.ToString());

// Find the intersection between two 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

Console.WriteLine("Displays the result of Intersect method :


");
Console.WriteLine(socketPermission1.ToString());

// Demand that the calling method have the requsite socket permission.
socketPermission1.Demand();

Remarks
If the SocketPermission instance is created with the Unrestricted value from PermissionState then the
SocketPermission instance passes all demands. Any other value for state results in a SocketPermission instance that
fails all demands unless a transport address permission is added with AddPermission.

SocketPermission(NetworkAccess, TransportType, String, Int32)


SocketPermission(NetworkAccess, TransportType, String, Int32)
Initializes a new instance of the SocketPermission class for the given transport address with the specified permission.

public SocketPermission (System.Net.NetworkAccess access, System.Net.TransportType transport, string


hostName, int portNumber);
new System.Net.SocketPermission : System.Net.NetworkAccess * System.Net.TransportType * string * int
-> System.Net.SocketPermission

Parameters
access NetworkAccess NetworkAccess
One of the NetworkAccess values.
transport TransportType TransportType
One of the TransportType values.
hostName String String
The host name for the transport address.
portNumber Int32 Int32
The port number for the transport address.
Exceptions
ArgumentNullException ArgumentNullException
hostName is null .
Examples
The following example creates a SocketPermission using a NetworkAccess enumerated value, a TransportType
enumerated value, the hostname, and the port number.
SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement1 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement2 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and
// for 'All'ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and
// for 'All' ports for the ip-address.
SecurityElement securityElement4 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement2.AddChild(securityElement3);
securityElement2.AddChild(securityElement4);
securityElement1.AddChild(securityElement2);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement1);

Console.WriteLine("
Displays the result of FromXml method :
");
Console.WriteLine(socketPermission2.ToString());

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for 'All'
ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("Displays the result of AddPermission method :


");
Console.WriteLine(socketPermission3.ToString());

// Find the intersection between two 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission2.Intersect(socketPermission3);

Console.WriteLine("Displays the result of Intersect method :


");
Console.WriteLine(socketPermission1.ToString());

// Demand that the calling method have the requsite socket permission.
socketPermission1.Demand();

Remarks
This constructor creates a SocketPermission that controls access to the specified hostName and portNumber using the
specified transport .

The hostName can be a DNS name, an IP address, or a specified IP subnet, such as 192.168.1.*.
The portNumber can be any valid port number defined by the transport, or SocketPermission.AllPorts.
SocketPermission.ToXml SocketPermission.ToXml
I n this Article
Creates an XML encoding of a SocketPermission instance and its current state.
public override System.Security.SecurityElement ToXml ();
override this.ToXml : unit -> System.Security.SecurityElement

Returns
SecurityElement SecurityElement
A SecurityElement instance that contains an XML -encoded representation of the SocketPermission instance, including
state information.

Examples
The following example uses the ToXml method to convert a SocketPermission to XML.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.Security;
using System.Security.Permissions;

public class DateClient {

private Socket serverSocket;


private Encoding asciiEncoding;
private IPAddress serverAddress;

private int serverPort;

// The constructor takes the address and port of the remote server.
public DateClient(IPAddress serverIpAddress, int port) {
serverAddress = serverIpAddress;
serverPort = port;
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
asciiEncoding = Encoding.ASCII;
}

// Print a security element and all its children, in a depth-first manner.


private void PrintSecurityElement(SecurityElement securityElementObj, int depth) {

Console.WriteLine("Depth : {0}", depth);


Console.WriteLine("Tag : {0}", securityElementObj.Tag);
Console.WriteLine("Text : {0}", securityElementObj.Text);
if(securityElementObj.Children != null)
Console.WriteLine("Children : {0}", securityElementObj.Children.Count);

if(securityElementObj.Attributes != null) {
IEnumerator attributeEnumerator = securityElementObj.Attributes.GetEnumerator();
while(attributeEnumerator.MoveNext())
Console.WriteLine("Attribute - \"{0}\" , Value - \"{1}\"",
((IDictionaryEnumerator)attributeEnumerator).Key,
((IDictionaryEnumerator)attributeEnumerator).Value);
}

Console.WriteLine("");
if(securityElementObj.Children != null) {
depth += 1;
for(int i = 0; i < securityElementObj.Children.Count; i++)
PrintSecurityElement((SecurityElement)(securityElementObj.Children[i]), depth);
}
}

public String GetDate()


{

SocketPermission socketPermission1 = new SocketPermission(PermissionState.Unrestricted);

// Create a 'SocketPermission' object for two ip addresses.


SocketPermission socketPermission2 = new SocketPermission(PermissionState.None);
SecurityElement securityElement4 = socketPermission2.ToXml();
// 'SocketPermission' object for 'Connect' permission
SecurityElement securityElement1 = new SecurityElement("ConnectAccess");
// Format to specify ip address are <ip-address>#<port>#<transport-type>
// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for
'All' ports for the ip-address.
SecurityElement securityElement2 = new SecurityElement("URI", "192.168.144.238#-1#3");
// Second 'SocketPermission' ip-address is '192.168.144.240' for 'All' transport types and for
'All' ports for the ip-address.
SecurityElement securityElement3 = new SecurityElement("URI", "192.168.144.240#-1#3");
securityElement1.AddChild(securityElement2);
securityElement1.AddChild(securityElement3);
securityElement4.AddChild(securityElement1);

// Obtain a 'SocketPermission' object using 'FromXml' method.


socketPermission2.FromXml(securityElement4);

// Create another 'SocketPermission' object with two ip addresses.


// First 'SocketPermission' ip-address is '192.168.144.238' for 'All' transport types and for
'All' ports for the ip-address.
SocketPermission socketPermission3 =
new SocketPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.238",
SocketPermission.AllPorts);

// Second 'SocketPermission' ip-address is '192.168.144.239' for 'All' transport types and for
'All' ports for the ip-address.
socketPermission3.AddPermission(NetworkAccess.Connect,
TransportType.All,
"192.168.144.239",
SocketPermission.AllPorts);

Console.WriteLine("
Checks the Socket permissions using IsUnrestricted method : ");
if(socketPermission1.IsUnrestricted())
Console.WriteLine("Socket permission is unrestricted");
else
Console.WriteLine("Socket permission is restricted");

Console.WriteLine();

Console.WriteLine("Display result of ConnectList property :


");
IEnumerator enumerator = socketPermission3.ConnectList;
while(enumerator.MoveNext()) {
Console.WriteLine("The hostname is : {0}",
((EndpointPermission)enumerator.Current).Hostname);
Console.WriteLine("The port is : {0}", ((EndpointPermission)enumerator.Current).Port);
Console.WriteLine("The Transport type is : {0}",
((EndpointPermission)enumerator.Current).Transport);
}
}
Console.WriteLine("");

Console.WriteLine("Display Security Elements :


");
PrintSecurityElement(socketPermission2.ToXml(), 0);

// Get a 'SocketPermission' object which is a union of two other 'SocketPermission' objects.


socketPermission1 = (SocketPermission)socketPermission3.Union(socketPermission2);

// Demand that the calling method have the socket permission.


socketPermission1.Demand();

// Get the current date from the remote date server.


try {
int bytesReceived;
byte[] getByte = new byte[100];
serverSocket.Connect(new IPEndPoint( serverAddress, serverPort));
bytesReceived = serverSocket.Receive( getByte, getByte.Length, 0 );
return asciiEncoding.GetString( getByte, 0, bytesReceived );
}
catch(Exception e)
{
Console.WriteLine("
Exception raised : {0}", e.Message);
return "";
}
}
};

Remarks
The ToXml method creates a SecurityElement instance to encode a representation of the SocketPermission instance,
including state information, in XML.
Use the FromXml method to restore the state information from a SecurityElement instance.
SocketPermission.Union SocketPermission.Union
I n this Article
Returns the logical union between two SocketPermission instances.
public override System.Security.IPermission Union (System.Security.IPermission target);
override this.Union : System.Security.IPermission -> System.Security.IPermission

Parameters
target IPermission IPermission
The SocketPermission instance to combine with the current instance.
Returns
IPermission IPermission
The SocketPermission instance that represents the union of two SocketPermission instances. If target parameter is
null , it returns a copy of the current instance.

Exceptions
ArgumentException ArgumentException
target is not a SocketPermission.

Examples
The following example uses the Union method to return the logical union of two existing SocketPermission instances.
// Creates a SocketPermission restricting access to and from all URIs.
SocketPermission mySocketPermission1 = new SocketPermission(PermissionState.None);

// The socket to which this permission will apply will allow connections from www.contoso.com.
mySocketPermission1.AddPermission(NetworkAccess.Accept, TransportType.Tcp, "www.contoso.com",
11000);

// Creates a SocketPermission which will allow the target Socket to connect with
www.southridgevideo.com.
SocketPermission mySocketPermission2 =
new SocketPermission(NetworkAccess.Connect, TransportType.Tcp,
"www.southridgevideo.com", 11002);

// Creates a SocketPermission from the union of two SocketPermissions.


SocketPermission mySocketPermissionUnion =
(SocketPermission)mySocketPermission1.Union(mySocketPermission2);

// Checks to see if the union was successfully created by using the IsSubsetOf method.
if (mySocketPermission1.IsSubsetOf(mySocketPermissionUnion) &&
mySocketPermission2.IsSubsetOf(mySocketPermissionUnion)){
Console.WriteLine("This union contains permissions from both mySocketPermission1 and
mySocketPermission2");

// Prints the allowable accept URIs to the console.


Console.WriteLine("This union accepts connections on :");

IEnumerator myEnumerator = mySocketPermissionUnion.AcceptList;


while (myEnumerator.MoveNext()) {
Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
}

// Prints the allowable connect URIs to the console.


Console.WriteLine("This union permits connections to :");

myEnumerator = mySocketPermissionUnion.ConnectList;
while (myEnumerator.MoveNext()) {
Console.WriteLine(((EndpointPermission)myEnumerator.Current).ToString());
}

Remarks
The result of a call to Union is a permission that represents all of the access to Socket connections represented by the
current instance as well as the access represented by target . Any demand that passes either the current instance or
target passes their union. This method overrides Union and is implemented to support the IPermission interface.
SocketPermissionAttribute SocketPermissionAttribute
Class
Specifies security actions to control Socket connections. This class cannot be inherited.

D eclaration
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Constructor | System.AttributeTargets.Method |
System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Struct | System.AttributeTargets.Constructor |
System.AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
[System.Serializable]
public sealed class SocketPermissionAttribute :
System.Security.Permissions.CodeAccessSecurityAttribute
type SocketPermissionAttribute = class
inherit CodeAccessSecurityAttribute

I nheritance H ierarchy
Object Object
Attribute Attribute
SecurityAttribute SecurityAttribute
CodeAccessSecurityAttribute CodeAccessSecurityAttribute

Remarks
To use this attribute, your Socket connection must conform to the properties that are specified in your
SocketPermissionAttribute. For example, to apply the permission to a Socket connection on port 80, set the Port
property of the SocketPermissionAttribute to "80". The security information that is specified in
SocketPermissionAttribute is stored in the metadata of the attribute target, which is the class to which the
SocketPermissionAttribute is applied. The system then accesses the information at run time. The SecurityAction that is
passed to the constructor determines the allowable SocketPermissionAttribute targets.
Note

The properties of a SocketPermissionAttribute must have values that are not null . Also, once set, the values of the
properties cannot be changed.
Note

For more information about using attributes, see Attributes.

Constructors
SocketPermissionAttribute(SecurityAction)
SocketPermissionAttribute(SecurityAction)

Initializes a new instance of the SocketPermissionAttribute class with the specified SecurityAction value.

Properties
Access
Access
Gets or sets the network access method that is allowed by this SocketPermissionAttribute.

Host
Host

Gets or sets the DNS host name or IP address that is specified by this SocketPermissionAttribute.

Port
Port

Gets or sets the port number that is associated with this SocketPermissionAttribute.

Transport
Transport

Gets or sets the TransportType that is specified by this SocketPermissionAttribute.

Methods
CreatePermission()
CreatePermission()

Creates and returns a new instance of the SocketPermission class.


SocketPermissionAttribute.Access SocketPermission
Attribute.Access
I n this Article
Gets or sets the network access method that is allowed by this SocketPermissionAttribute.

public string Access { get; set; }


member this.Access : string with get, set

Returns
String String
A string that contains the network access method that is allowed by this instance of SocketPermissionAttribute. Valid
values are "Accept" and "Connect."
Exceptions
ArgumentException ArgumentException
The Access property is not null when you attempt to set the value. To specify more than one Access method, use an
additional attribute declaration statement.

Remarks
This property is write-once. Valid values for this property correspond to NetworkAccess enumeration values.
SocketPermissionAttribute.CreatePermission Socket
PermissionAttribute.CreatePermission
I n this Article
Creates and returns a new instance of the SocketPermission class.

public override System.Security.IPermission CreatePermission ();


override this.CreatePermission : unit -> System.Security.IPermission

Returns
IPermission IPermission
An instance of the SocketPermission class that corresponds to the security declaration.
Exceptions
ArgumentException ArgumentException
One or more of the current instance's Access, Host, Transport, or Port properties is null .

Remarks
The CreatePermission method is called by the security system, not by the application code. The security information
described by SocketPermissionAttribute is stored in the metadata of the attribute target, which is the class to which the
SocketPermissionAttribute is applied. The system then accesses the information at run-time and calls
CreatePermission. The system uses the returned IPermission to enforce the specified security requirements.
SocketPermissionAttribute.Host SocketPermission
Attribute.Host
I n this Article
Gets or sets the DNS host name or IP address that is specified by this SocketPermissionAttribute.

public string Host { get; set; }


member this.Host : string with get, set

Returns
String String
A string that contains the DNS host name or IP address that is associated with this instance of
SocketPermissionAttribute.
Exceptions
ArgumentException ArgumentException
Host is not null when you attempt to set the value. To specify more than one host, use an additional attribute
declaration statement.

Remarks
This property is write-once and specifies the Domain Name Services (DNS ) host name to which this permission
applies.
SocketPermissionAttribute.Port SocketPermission
Attribute.Port
I n this Article
Gets or sets the port number that is associated with this SocketPermissionAttribute.

public string Port { get; set; }


member this.Port : string with get, set

Returns
String String
A string that contains the port number that is associated with this instance of SocketPermissionAttribute.
Exceptions
ArgumentException ArgumentException
The Port property is null when you attempt to set the value. To specify more than one port, use an additional attribute
declaration statement.

Remarks
This property is write-once and specifies the port number to which this permission applies. The valid values are a
string-encoded integer or the string "All".
SocketPermissionAttribute SocketPermissionAttribute
I n this Article
Initializes a new instance of the SocketPermissionAttribute class with the specified SecurityAction value.
public SocketPermissionAttribute (System.Security.Permissions.SecurityAction action);
new System.Net.SocketPermissionAttribute : System.Security.Permissions.SecurityAction ->
System.Net.SocketPermissionAttribute

Parameters
action SecurityAction SecurityAction
One of the SecurityAction values.
Exceptions
ArgumentException ArgumentException
action is not a valid SecurityAction value.

Remarks
The SecurityAction value that is passed to this constructor specifies the allowable SocketPermissionAttribute targets.
SocketPermissionAttribute.Transport SocketPermission
Attribute.Transport
I n this Article
Gets or sets the TransportType that is specified by this SocketPermissionAttribute.

public string Transport { get; set; }


member this.Transport : string with get, set

Returns
String String
A string that contains the TransportType that is associated with this SocketPermissionAttribute.
Exceptions
ArgumentException ArgumentException
Transport is not null when you attempt to set the value. To specify more than one transport type, use an additional
attribute declaration statement.

Remarks
Possible string values of this property are All, Connectionless, ConnectionOriented, Tcp, and Udp.
TransportContext TransportContext Class
The TransportContext class provides additional context about the underlying transport layer.

D eclaration
public abstract class TransportContext
type TransportContext = class

I nheritance H ierarchy
Object Object

Remarks
The TransportContext class is used with classes in the System.Security.Authentication.ExtendedProtection namespace
to provide support for authentication using extended protection for applications.
The design of integrated Windows authentication allows for some credential challenge responses to be universal,
meaning they can be re-used or forwarded. If this particular design feature is not needed then the challenge responses
should be constructed with, at minimum, target specific information and, at best, also some channel specific
information. Services can then provide extended protection to ensure that credential challenge responses contain
service specific information (a Service Provider Name or SPN ) and, if necessary, channel specific information (a
channel binding token or CBT). With this information in the credential exchanges, services are able to better protect
against malicious use of credential challenge responses that might have been improperly obtained.
HttpWebRequest is the only class derived from WebRequest class that can potentially use IWA. The FtpWebRequest
class does only FTP clear text authentication. The FileWebRequest class doesn't perform any authentication.
There are several ways an application may get a TransportContext instance. An application that uses SslStream can get
the TransportContext using the TransportContext property. An application that uses HttpWebRequest can get a
TransportContext using the GetRequestStream or EndGetRequestStream methods.

Constructors
TransportContext()
TransportContext()

Creates a new instance of the TransportContext class

Methods
GetChannelBinding(ChannelBindingKind)
GetChannelBinding(ChannelBindingKind)

Retrieves the requested channel binding.

GetTlsTokenBindings()
GetTlsTokenBindings()

Gets the transport security layer token bindings.


See Also
ChannelBinding ChannelBinding
ChannelBinding ChannelBinding
TransportContext.GetChannelBinding TransportContext.
GetChannelBinding
I n this Article
Retrieves the requested channel binding.

public abstract System.Security.Authentication.ExtendedProtection.ChannelBinding GetChannelBinding


(System.Security.Authentication.ExtendedProtection.ChannelBindingKind kind);
abstract member GetChannelBinding :
System.Security.Authentication.ExtendedProtection.ChannelBindingKind ->
System.Security.Authentication.ExtendedProtection.ChannelBinding

Parameters
kind ChannelBindingKind ChannelBindingKind
The type of channel binding to retrieve.
Returns
ChannelBinding ChannelBinding
The requested ChannelBinding, or null if the channel binding is not supported by the current transport or by the
operating system.
Exceptions
NotSupportedException NotSupportedException
kind is must be Endpoint for use with the TransportContext retrieved from the TransportContext property.

Remarks
The possible values for the kind parameter are Endpoint or Unique.
If an application attempts to retrieve the channel binding token (CBT) from the TransportContext property using the
GetChannelBinding method and the ChannelBindingKind is not Endpoint, then the HttpListenerRequest will throw
NotSupportedException. The HttpListenerRequest overrides the GetChannelBinding method with an internal
implementation
See ChannelBindingChannelBinding
Also
TransportContext.GetTlsTokenBindings TransportContext.
GetTlsTokenBindings
I n this Article
Gets the transport security layer token bindings.

public virtual
System.Collections.Generic.IEnumerable<System.Security.Authentication.ExtendedProtection.TokenBindin
g> GetTlsTokenBindings ();
abstract member GetTlsTokenBindings : unit ->
seq<System.Security.Authentication.ExtendedProtection.TokenBinding>
override this.GetTlsTokenBindings : unit ->
seq<System.Security.Authentication.ExtendedProtection.TokenBinding>

Returns
IEnumerable<TokenBinding>
The transport security layer token bindings.
TransportContext
I n this Article
Creates a new instance of the TransportContext class
protected TransportContext ();
TransportType TransportType Enum
Defines transport types for the SocketPermission and Socket classes.

D eclaration
public enum TransportType
type TransportType =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The TransportType enumeration defines transport types for the SocketPermission and Socket classes.

Fields
All All All transport types.

Connectionless The transport type is connectionless, such as UDP. Specifying this value has the same
Connectionless effect as specifying Udp.

ConnectionOriented The transport is connection oriented, such as TCP. Specifying this value has the same
ConnectionOriented effect as specifying Tcp.

Tcp Tcp TCP transport.

Udp Udp UDP transport.


UiSynchronizationContext UiSynchronizationContext
Class
Provides the synchronization context for the managed UI used in synchronization models.

D eclaration
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be
used directly from your code.", true)]
public static class UiSynchronizationContext
type UiSynchronizationContext = class

I nheritance H ierarchy
Object Object

Properties
Current
Current

Gets the synchronization context for the current thread.

ManagedUiThreadId
ManagedUiThreadId

Gets a unique identifier for the current managed thread.


UiSynchronizationContext.Current UiSynchronization
Context.Current
I n this Article
Gets the synchronization context for the current thread.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public static System.Threading.SynchronizationContext Current { get; set; }
member this.Current : System.Threading.SynchronizationContext with get, set

Returns
SynchronizationContext SynchronizationContext
Returns SynchronizationContext.
The synchronization context for the current thread.
Attributes ObsoleteAttribute
UiSynchronizationContext.ManagedUiThreadId Ui
SynchronizationContext.ManagedUiThreadId
I n this Article
Gets a unique identifier for the current managed thread.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public static int ManagedUiThreadId { get; set; }
member this.ManagedUiThreadId : int with get, set

Returns
Int32 Int32
Returns Int32.
An integer that represents a unique identifier for this managed thread.
Attributes ObsoleteAttribute
UploadDataCompletedEventArgs UploadDataCompleted
EventArgs Class
Provides data for the UploadDataCompleted event.

D eclaration
public class UploadDataCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type UploadDataCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to the UploadDataCompletedEventHandler.

Properties
Result
Result

Gets the server reply to a data upload operation started by calling an UploadDataAsync method.
UploadDataCompletedEventArgs.Result UploadData
CompletedEventArgs.Result
I n this Article
Gets the server reply to a data upload operation started by calling an UploadDataAsync method.

public byte[] Result { get; }


member this.Result : byte[]

Returns
Byte[]
A Byte array containing the server reply.

Examples
The following code example displays the value of this property.
private static void UploadDataCallback2 (Object sender, UploadDataCompletedEventArgs e)
{
byte[] data = (byte[])e.Result;
string reply = System.Text.Encoding.UTF8.GetString (data);

Console.WriteLine (reply);
}

Remarks
You should check the Error and Cancelled properties before using the data returned by this property. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
UploadDataCompletedEventHandler UploadData
CompletedEventHandler Delegate
Represents the method that will handle the UploadDataCompleted event of a WebClient.

D eclaration
public delegate void UploadDataCompletedEventHandler(object sender, UploadDataCompletedEventArgs
e);
type UploadDataCompletedEventHandler = delegate of obj * UploadDataCompletedEventArgs -> unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a UploadDataCompletedEventHandler delegate, you identify the method that will handle the event.
To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see
Handling and Raising Events.
UploadFileCompletedEventArgs UploadFileCompleted
EventArgs Class
Provides data for the UploadFileCompleted event.

D eclaration
public class UploadFileCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type UploadFileCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to the UploadFileCompletedEventHandler.

Properties
Result
Result

Gets the server reply to a data upload operation that is started by calling an UploadFileAsync method.
UploadFileCompletedEventArgs.Result UploadFile
CompletedEventArgs.Result
I n this Article
Gets the server reply to a data upload operation that is started by calling an UploadFileAsync method.

public byte[] Result { get; }


member this.Result : byte[]

Returns
Byte[]
A Byte array that contains the server reply.

Examples
The following code example displays the value of this property.
private static void UploadFileCallback2 (Object sender, UploadFileCompletedEventArgs e)
{
string reply = System.Text.Encoding.UTF8.GetString (e.Result);
Console.WriteLine (reply);
}

Remarks
You should check the Error and Cancelled properties to determine whether the upload completed. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
UploadFileCompletedEventHandler UploadFile
CompletedEventHandler Delegate
Represents the method that will handle the UploadFileCompleted event of a WebClient.

D eclaration
public delegate void UploadFileCompletedEventHandler(object sender, UploadFileCompletedEventArgs
e);
type UploadFileCompletedEventHandler = delegate of obj * UploadFileCompletedEventArgs -> unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a UploadFileCompletedEventHandler delegate, you identify the method that will handle the event. To
associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see
Handling and Raising Events.
UploadProgressChangedEventArgs UploadProgress
ChangedEventArgs Class
Provides data for the UploadProgressChanged event of a WebClient.

D eclaration
public class UploadProgressChangedEventArgs : System.ComponentModel.ProgressChangedEventArgs
type UploadProgressChangedEventArgs = class
inherit ProgressChangedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
ProgressChangedEventArgs ProgressChangedEventArgs

Remarks
Instances of this class are passed to the UploadProgressChangedEventHandler.

Properties
BytesReceived
BytesReceived

Gets the number of bytes received.

BytesSent
BytesSent

Gets the number of bytes sent.

TotalBytesToReceive
TotalBytesToReceive

Gets the total number of bytes in a WebClient data upload operation.

TotalBytesToSend
TotalBytesToSend

Gets the total number of bytes to send.


UploadProgressChangedEventArgs.BytesReceived
UploadProgressChangedEventArgs.BytesReceived
I n this Article
Gets the number of bytes received.

public long BytesReceived { get; }


member this.BytesReceived : int64

Returns
Int64 Int64
An Int64 value that indicates the number of bytes received.

Remarks
Uploading data to a server may result in a download from the server. For example, suppose your application uploads a
POST request to a Web server. The resulting download will update BytesReceived and TotalBytesToReceive.
To determine what percentage of the transfer has occurred, use the ProgressPercentage property. When the upload is
complete, ProgressPercentage will be 50%. When the download completes, ProgressPercentage will be 100%.
UploadProgressChangedEventArgs.BytesSent Upload
ProgressChangedEventArgs.BytesSent
I n this Article
Gets the number of bytes sent.

public long BytesSent { get; }


member this.BytesSent : int64

Returns
Int64 Int64
An Int64 value that indicates the number of bytes sent.

Remarks
Uploading data to a server may result in a download from the server. For example, suppose your application uploads a
POST request to a Web server. The resulting download will update BytesReceived and TotalBytesToReceive.
To determine what percentage of the transfer has occurred, use the ProgressPercentage property. When the upload is
complete, ProgressPercentage will be 50%. When the download completes, ProgressPercentage will be 100%.
UploadProgressChangedEventArgs.TotalBytesToReceive
UploadProgressChangedEventArgs.TotalBytesToReceive
I n this Article
Gets the total number of bytes in a WebClient data upload operation.

public long TotalBytesToReceive { get; }


member this.TotalBytesToReceive : int64

Returns
Int64 Int64
An Int64 value that indicates the number of bytes that will be received.

Remarks
To determine the number of bytes already received, use the BytesReceived property.
Uploading data to a server may result in a download from the server. For example, suppose your application uploads a
POST request to a Web server. The resulting download will update BytesReceived and TotalBytesToReceive.
To determine what percentage of the transfer has occurred, use the ProgressPercentage property. When the upload is
complete, ProgressPercentage will be 50%. When the download completes, ProgressPercentage will be 100%.
UploadProgressChangedEventArgs.TotalBytesToSend
UploadProgressChangedEventArgs.TotalBytesToSend
I n this Article
Gets the total number of bytes to send.

public long TotalBytesToSend { get; }


member this.TotalBytesToSend : int64

Returns
Int64 Int64
An Int64 value that indicates the number of bytes that will be sent.

Remarks
To determine the number of bytes already sent, use the BytesSent property.
Uploading data to a server may result in a download from the server. For example, suppose your application uploads a
POST request to a Web server. The resulting download will update BytesReceived and TotalBytesToReceive.
To determine what percentage of the transfer has occurred, use the ProgressPercentage property. When the upload is
complete, ProgressPercentage will be 50%. When the download completes, ProgressPercentage will be 100%.
UploadProgressChangedEventHandler UploadProgress
ChangedEventHandler Delegate
Represents the method that will handle the UploadProgressChanged event of a WebClient.

D eclaration
public delegate void UploadProgressChangedEventHandler(object sender,
UploadProgressChangedEventArgs e);
type UploadProgressChangedEventHandler = delegate of obj * UploadProgressChangedEventArgs ->
unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a UploadProgressChangedEventHandler delegate, you identify the method that will handle the event.
To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see
Handling and Raising Events.
UploadStringCompletedEventArgs UploadString
CompletedEventArgs Class
Provides data for the UploadStringCompleted event.

D eclaration
public class UploadStringCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type UploadStringCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to the UploadStringCompletedEventHandler.

Properties
Result
Result

Gets the server reply to a string upload operation that is started by calling an UploadStringAsync method.
UploadStringCompletedEventArgs.Result UploadString
CompletedEventArgs.Result
I n this Article
Gets the server reply to a string upload operation that is started by calling an UploadStringAsync method.

public string Result { get; }


member this.Result : string

Returns
String String
A Byte array that contains the server reply.

Examples
The following code example displays the value of this property.
private static void UploadStringCallback2 (Object sender, UploadStringCompletedEventArgs e)
{
string reply = (string)e.Result;
Console.WriteLine (reply);
}

Remarks
You should check the Error and Cancelled properties to determine whether the upload completed. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
UploadStringCompletedEventHandler UploadString
CompletedEventHandler Delegate
Represents the method that will handle the UploadStringCompleted event of a WebClient.

D eclaration
public delegate void UploadStringCompletedEventHandler(object sender,
UploadStringCompletedEventArgs e);
type UploadStringCompletedEventHandler = delegate of obj * UploadStringCompletedEventArgs ->
unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a UploadStringCompletedEventHandler delegate, you identify the method that will handle the event.
To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see
Handling and Raising Events.
UploadValuesCompletedEventArgs UploadValues
CompletedEventArgs Class
Provides data for the UploadValuesCompleted event.

D eclaration
public class UploadValuesCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs
type UploadValuesCompletedEventArgs = class
inherit AsyncCompletedEventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs
AsyncCompletedEventArgs AsyncCompletedEventArgs

Remarks
Instances of this class are passed to the UploadValuesCompletedEventHandler.

Properties
Result
Result

Gets the server reply to a data upload operation started by calling an UploadValuesAsync method.
UploadValuesCompletedEventArgs.Result UploadValues
CompletedEventArgs.Result
I n this Article
Gets the server reply to a data upload operation started by calling an UploadValuesAsync method.

public byte[] Result { get; }


member this.Result : byte[]

Returns
Byte[]
A Byte array containing the server reply.

Remarks
You should check the Error and Cancelled properties to determine whether the upload completed. If the Error
property's value is an Exception object or the Cancelled property's value is true , the asynchronous operation did not
complete correctly and the Result property's value will not be valid.
UploadValuesCompletedEventHandler UploadValues
CompletedEventHandler Delegate
Represents the method that will handle the UploadValuesCompleted event of a WebClient.

D eclaration
public delegate void UploadValuesCompletedEventHandler(object sender,
UploadValuesCompletedEventArgs e);
type UploadValuesCompletedEventHandler = delegate of obj * UploadValuesCompletedEventArgs ->
unit

I nheritance H ierarchy
Object Object
Delegate Delegate

Remarks
When you create a UploadValuesCompletedEventHandler delegate, you identify the method that will handle the event.
To associate the event with your event handler, add an instance of the delegate to the event. The event handler is called
whenever the event occurs, unless you remove the delegate. For more information about event handler delegates, see
Handling and Raising Events.
WebClient WebClient Class
Provides common methods for sending data to and receiving data from a resource identified by a URI.

D eclaration
[System.Runtime.InteropServices.ComVisible(true)]
public class WebClient : System.ComponentModel.Component
type WebClient = class
inherit Component

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject
Component Component

Remarks
Im p o rt a nt

We don't recommend that you use the WebClient class for new development. Instead, use the
System.Net.Http.HttpClient class.
The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or
Internet resource identified by a URI.
The WebClient class uses the WebRequest class to provide access to resources. WebClient instances can access data
with any WebRequest descendant registered with the WebRequest.RegisterPrefix method.
Note

By default, the .NET Framework supports URIs that begin with http: , https: , ftp: , and file: scheme identifiers.
The following table describes WebClient methods for uploading data to a resource.

ME THO D D ES CR IPTIO N

OpenWrite Retrieves a Stream used to send data to the resource.

OpenWriteAsync Retrieves a Stream used to send data to the resource, without


blocking the calling thread.

UploadData Sends a byte array to the resource and returns a Byte array
containing any response.

UploadDataAsync Sends a Byte array to the resource, without blocking the


calling thread.

UploadFile Sends a local file to the resource and returns a Byte array
containing any response.

UploadFileAsync Sends a local file to the resource, without blocking the calling
thread.
ME THO D D ES CR IPTIO N

UploadValues Sends a NameValueCollection to the resource and returns a


Byte array containing any response.

UploadValuesAsync Sends a NameValueCollection to the resource and returns a


Byte array containing any response, without blocking the
calling thread.

UploadString Sends a String to the resource, without blocking the calling


thread.

UploadStringAsync Sends a String to the resource, without blocking the calling


thread.

The following table describes WebClient methods for downloading data from a resource.

ME THO D D ES CR IPTIO N

OpenRead Returns the data from a resource as a Stream.

OpenReadAsync Returns the data from a resource, without blocking the calling
thread.

DownloadData Downloads data from a resource and returns a Byte array.

DownloadDataAsync Downloads data from a resource and returns a Byte array,


without blocking the calling thread.

DownloadFile Downloads data from a resource to a local file.

DownloadFileAsync Downloads data from a resource to a local file, without


blocking the calling thread.

DownloadString Downloads a String from a resource and returns a String.

DownloadStringAsync Downloads a String from a resource, without blocking the


calling thread.

You can use the CancelAsync method to cancel asynchronous operations that have not completed.
A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you
must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-
agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing.
AllowAutoRedirect is set to true in WebClient instances.

Constructors
WebClient()
WebClient()

Initializes a new instance of the WebClient class.


Properties
AllowReadStreamBuffering
AllowReadStreamBuffering

Gets or sets a value that indicates whether to buffer the data read from the Internet resource for a WebClient
instance.

AllowWriteStreamBuffering
AllowWriteStreamBuffering

Gets or sets a value that indicates whether to buffer the data written to the Internet resource for a WebClient
instance.

BaseAddress
BaseAddress

Gets or sets the base URI for requests made by a WebClient.

CachePolicy
CachePolicy

Gets or sets the application's cache policy for any resources obtained by this WebClient instance using
WebRequest objects.

Credentials
Credentials

Gets or sets the network credentials that are sent to the host and used to authenticate the request.

Encoding
Encoding

Gets or sets the Encoding used to upload and download strings.

Headers
Headers

Gets or sets a collection of header name/value pairs associated with the request.

IsBusy
IsBusy

Gets whether a Web request is in progress.


Proxy
Proxy

Gets or sets the proxy used by this WebClient object.

QueryString
QueryString

Gets or sets a collection of query name/value pairs associated with the request.

ResponseHeaders
ResponseHeaders

Gets a collection of header name/value pairs associated with the response.

UseDefaultCredentials
UseDefaultCredentials

Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

Methods
CancelAsync()
CancelAsync()

Cancels a pending asynchronous operation.

DownloadData(String)
DownloadData(String)

Downloads the resource as a Byte array from the URI specified.

DownloadData(Uri)
DownloadData(Uri)

Downloads the resource as a Byte array from the URI specified.

DownloadDataAsync(Uri)
DownloadDataAsync(Uri)

Downloads the resource as a Byte array from the URI specified as an asynchronous operation.

DownloadDataAsync(Uri, Object)
DownloadDataAsync(Uri, Object)

Downloads the resource as a Byte array from the URI specified as an asynchronous operation.
DownloadDataTaskAsync(String)
DownloadDataTaskAsync(String)

Downloads the resource as a Byte array from the URI specified as an asynchronous operation using a task object.

DownloadDataTaskAsync(Uri)
DownloadDataTaskAsync(Uri)

Downloads the resource as a Byte array from the URI specified as an asynchronous operation using a task object.

DownloadFile(Uri, String)
DownloadFile(Uri, String)

Downloads the resource with the specified URI to a local file.

DownloadFile(String, String)
DownloadFile(String, String)

Downloads the resource with the specified URI to a local file.

DownloadFileAsync(Uri, String)
DownloadFileAsync(Uri, String)

Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.

DownloadFileAsync(Uri, String, Object)


DownloadFileAsync(Uri, String, Object)

Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.

DownloadFileTaskAsync(String, String)
DownloadFileTaskAsync(String, String)

Downloads the specified resource to a local file as an asynchronous operation using a task object.

DownloadFileTaskAsync(Uri, String)
DownloadFileTaskAsync(Uri, String)

Downloads the specified resource to a local file as an asynchronous operation using a task object.

DownloadString(String)
DownloadString(String)

Downloads the requested resource as a String. The resource to download is specified as a String containing the
URI.
DownloadString(Uri)
DownloadString(Uri)

Downloads the requested resource as a String. The resource to download is specified as a Uri.

DownloadStringAsync(Uri)
DownloadStringAsync(Uri)

Downloads the resource specified as a Uri. This method does not block the calling thread.

DownloadStringAsync(Uri, Object)
DownloadStringAsync(Uri, Object)

Downloads the specified string to the specified resource. This method does not block the calling thread.

DownloadStringTaskAsync(String)
DownloadStringTaskAsync(String)

Downloads the resource as a String from the URI specified as an asynchronous operation using a task object.

DownloadStringTaskAsync(Uri)
DownloadStringTaskAsync(Uri)

Downloads the resource as a String from the URI specified as an asynchronous operation using a task object.

GetWebRequest(Uri)
GetWebRequest(Uri)

Returns a WebRequest object for the specified resource.

GetWebResponse(WebRequest)
GetWebResponse(WebRequest)

Returns the WebResponse for the specified WebRequest.

GetWebResponse(WebRequest, IAsyncResult)
GetWebResponse(WebRequest, IAsyncResult)

Returns the WebResponse for the specified WebRequest using the specified IAsyncResult.

OnDownloadDataCompleted(DownloadDataCompletedEventArgs)
OnDownloadDataCompleted(DownloadDataCompletedEventArgs)

Raises the DownloadDataCompleted event.


OnDownloadFileCompleted(AsyncCompletedEventArgs)
OnDownloadFileCompleted(AsyncCompletedEventArgs)

Raises the DownloadFileCompleted event.

OnDownloadProgressChanged(DownloadProgressChangedEventArgs)
OnDownloadProgressChanged(DownloadProgressChangedEventArgs)

Raises the DownloadProgressChanged event.

OnDownloadStringCompleted(DownloadStringCompletedEventArgs)
OnDownloadStringCompleted(DownloadStringCompletedEventArgs)

Raises the DownloadStringCompleted event.

OnOpenReadCompleted(OpenReadCompletedEventArgs)
OnOpenReadCompleted(OpenReadCompletedEventArgs)

Raises the OpenReadCompleted event.

OnOpenWriteCompleted(OpenWriteCompletedEventArgs)
OnOpenWriteCompleted(OpenWriteCompletedEventArgs)

Raises the OpenWriteCompleted event.

OnUploadDataCompleted(UploadDataCompletedEventArgs)
OnUploadDataCompleted(UploadDataCompletedEventArgs)

Raises the UploadDataCompleted event.

OnUploadFileCompleted(UploadFileCompletedEventArgs)
OnUploadFileCompleted(UploadFileCompletedEventArgs)

Raises the UploadFileCompleted event.

OnUploadProgressChanged(UploadProgressChangedEventArgs)
OnUploadProgressChanged(UploadProgressChangedEventArgs)

Raises the UploadProgressChanged event.

OnUploadStringCompleted(UploadStringCompletedEventArgs)
OnUploadStringCompleted(UploadStringCompletedEventArgs)

Raises the UploadStringCompleted event.


OnUploadValuesCompleted(UploadValuesCompletedEventArgs)
OnUploadValuesCompleted(UploadValuesCompletedEventArgs)

Raises the UploadValuesCompleted event.

OnWriteStreamClosed(WriteStreamClosedEventArgs)
OnWriteStreamClosed(WriteStreamClosedEventArgs)

Raises the WriteStreamClosed event.

OpenRead(String)
OpenRead(String)

Opens a readable stream for the data downloaded from a resource with the URI specified as a String.

OpenRead(Uri)
OpenRead(Uri)

Opens a readable stream for the data downloaded from a resource with the URI specified as a Uri

OpenReadAsync(Uri)
OpenReadAsync(Uri)

Opens a readable stream containing the specified resource. This method does not block the calling thread.

OpenReadAsync(Uri, Object)
OpenReadAsync(Uri, Object)

Opens a readable stream containing the specified resource. This method does not block the calling thread.

OpenReadTaskAsync(String)
OpenReadTaskAsync(String)

Opens a readable stream containing the specified resource as an asynchronous operation using a task object.

OpenReadTaskAsync(Uri)
OpenReadTaskAsync(Uri)

Opens a readable stream containing the specified resource as an asynchronous operation using a task object.

OpenWrite(String)
OpenWrite(String)

Opens a stream for writing data to the specified resource.


OpenWrite(Uri)
OpenWrite(Uri)

Opens a stream for writing data to the specified resource.

OpenWrite(String, String)
OpenWrite(String, String)

Opens a stream for writing data to the specified resource, using the specified method.

OpenWrite(Uri, String)
OpenWrite(Uri, String)

Opens a stream for writing data to the specified resource, by using the specified method.

OpenWriteAsync(Uri, String, Object)


OpenWriteAsync(Uri, String, Object)

Opens a stream for writing data to the specified resource, using the specified method. This method does not block
the calling thread.

OpenWriteAsync(Uri, String)
OpenWriteAsync(Uri, String)

Opens a stream for writing data to the specified resource. This method does not block the calling thread.

OpenWriteAsync(Uri)
OpenWriteAsync(Uri)

Opens a stream for writing data to the specified resource. This method does not block the calling thread.

OpenWriteTaskAsync(String)
OpenWriteTaskAsync(String)

Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.

OpenWriteTaskAsync(Uri)
OpenWriteTaskAsync(Uri)

Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.

OpenWriteTaskAsync(String, String)
OpenWriteTaskAsync(String, String)

Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.
OpenWriteTaskAsync(Uri, String)
OpenWriteTaskAsync(Uri, String)

Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.

UploadData(String, Byte[])
UploadData(String, Byte[])

Uploads a data buffer to a resource identified by a URI.

UploadData(Uri, Byte[])
UploadData(Uri, Byte[])

Uploads a data buffer to a resource identified by a URI.

UploadData(String, String, Byte[])


UploadData(String, String, Byte[])

Uploads a data buffer to the specified resource, using the specified method.

UploadData(Uri, String, Byte[])


UploadData(Uri, String, Byte[])

Uploads a data buffer to the specified resource, using the specified method.

UploadDataAsync(Uri, String, Byte[])


UploadDataAsync(Uri, String, Byte[])

Uploads a data buffer to a resource identified by a URI, using the specified method. This method does not block
the calling thread.

UploadDataAsync(Uri, String, Byte[], Object)


UploadDataAsync(Uri, String, Byte[], Object)

Uploads a data buffer to a resource identified by a URI, using the specified method and identifying token.

UploadDataAsync(Uri, Byte[])
UploadDataAsync(Uri, Byte[])

Uploads a data buffer to a resource identified by a URI, using the POST method. This method does not block the
calling thread.

UploadDataTaskAsync(String, Byte[])
UploadDataTaskAsync(String, Byte[])

Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task
object.

UploadDataTaskAsync(Uri, Byte[])
UploadDataTaskAsync(Uri, Byte[])

Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task
object.

UploadDataTaskAsync(String, String, Byte[])


UploadDataTaskAsync(String, String, Byte[])

Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task
object.

UploadDataTaskAsync(Uri, String, Byte[])


UploadDataTaskAsync(Uri, String, Byte[])

Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task
object.

UploadFile(String, String)
UploadFile(String, String)

Uploads the specified local file to a resource with the specified URI.

UploadFile(Uri, String)
UploadFile(Uri, String)

Uploads the specified local file to a resource with the specified URI.

UploadFile(String, String, String)


UploadFile(String, String, String)

Uploads the specified local file to the specified resource, using the specified method.

UploadFile(Uri, String, String)


UploadFile(Uri, String, String)

Uploads the specified local file to the specified resource, using the specified method.

UploadFileAsync(Uri, String)
UploadFileAsync(Uri, String)

Uploads the specified local file to the specified resource, using the POST method. This method does not block the
calling thread.
UploadFileAsync(Uri, String, String)
UploadFileAsync(Uri, String, String)

Uploads the specified local file to the specified resource, using the POST method. This method does not block the
calling thread.

UploadFileAsync(Uri, String, String, Object)


UploadFileAsync(Uri, String, String, Object)

Uploads the specified local file to the specified resource, using the POST method. This method does not block the
calling thread.

UploadFileTaskAsync(Uri, String, String)


UploadFileTaskAsync(Uri, String, String)

Uploads the specified local file to a resource as an asynchronous operation using a task object.

UploadFileTaskAsync(String, String, String)


UploadFileTaskAsync(String, String, String)

Uploads the specified local file to a resource as an asynchronous operation using a task object.

UploadFileTaskAsync(String, String)
UploadFileTaskAsync(String, String)

Uploads the specified local file to a resource as an asynchronous operation using a task object.

UploadFileTaskAsync(Uri, String)
UploadFileTaskAsync(Uri, String)

Uploads the specified local file to a resource as an asynchronous operation using a task object.

UploadString(String, String)
UploadString(String, String)

Uploads the specified string to the specified resource, using the POST method.

UploadString(Uri, String)
UploadString(Uri, String)

Uploads the specified string to the specified resource, using the POST method.

UploadString(String, String, String)


UploadString(String, String, String)

Uploads the specified string to the specified resource, using the specified method.
UploadString(Uri, String, String)
UploadString(Uri, String, String)

Uploads the specified string to the specified resource, using the specified method.

UploadStringAsync(Uri, String)
UploadStringAsync(Uri, String)

Uploads the specified string to the specified resource. This method does not block the calling thread.

UploadStringAsync(Uri, String, String)


UploadStringAsync(Uri, String, String)

Uploads the specified string to the specified resource. This method does not block the calling thread.

UploadStringAsync(Uri, String, String, Object)


UploadStringAsync(Uri, String, String, Object)

Uploads the specified string to the specified resource. This method does not block the calling thread.

UploadStringTaskAsync(Uri, String, String)


UploadStringTaskAsync(Uri, String, String)

Uploads the specified string to the specified resource as an asynchronous operation using a task object.

UploadStringTaskAsync(String, String, String)


UploadStringTaskAsync(String, String, String)

Uploads the specified string to the specified resource as an asynchronous operation using a task object.

UploadStringTaskAsync(String, String)
UploadStringTaskAsync(String, String)

Uploads the specified string to the specified resource as an asynchronous operation using a task object.

UploadStringTaskAsync(Uri, String)
UploadStringTaskAsync(Uri, String)

Uploads the specified string to the specified resource as an asynchronous operation using a task object.

UploadValues(String, NameValueCollection)
UploadValues(String, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI.

UploadValues(Uri, NameValueCollection)
UploadValues(Uri, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI.

UploadValues(String, String, NameValueCollection)


UploadValues(String, String, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI, using the specified
method.

UploadValues(Uri, String, NameValueCollection)


UploadValues(Uri, String, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI, using the specified
method.

UploadValuesAsync(Uri, NameValueCollection)
UploadValuesAsync(Uri, NameValueCollection)

Uploads the data in the specified name/value collection to the resource identified by the specified URI. This
method does not block the calling thread.

UploadValuesAsync(Uri, String, NameValueCollection)


UploadValuesAsync(Uri, String, NameValueCollection)

Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the
specified method. This method does not block the calling thread.

UploadValuesAsync(Uri, String, NameValueCollection, Object)


UploadValuesAsync(Uri, String, NameValueCollection, Object)

Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the
specified method. This method does not block the calling thread, and allows the caller to pass an object to the
method that is invoked when the operation completes.

UploadValuesTaskAsync(String, String, NameValueCollection)


UploadValuesTaskAsync(String, String, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.
UploadValuesTaskAsync(String, NameValueCollection)
UploadValuesTaskAsync(String, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.

UploadValuesTaskAsync(Uri, NameValueCollection)
UploadValuesTaskAsync(Uri, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.

UploadValuesTaskAsync(Uri, String, NameValueCollection)


UploadValuesTaskAsync(Uri, String, NameValueCollection)

Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.

Events
DownloadDataCompleted
DownloadDataCompleted

Occurs when an asynchronous data download operation completes.

DownloadFileCompleted
DownloadFileCompleted

Occurs when an asynchronous file download operation completes.

DownloadProgressChanged
DownloadProgressChanged

Occurs when an asynchronous download operation successfully transfers some or all of the data.

DownloadStringCompleted
DownloadStringCompleted

Occurs when an asynchronous resource-download operation completes.

OpenReadCompleted
OpenReadCompleted

Occurs when an asynchronous operation to open a stream containing a resource completes.


OpenWriteCompleted
OpenWriteCompleted

Occurs when an asynchronous operation to open a stream to write data to a resource completes.

UploadDataCompleted
UploadDataCompleted

Occurs when an asynchronous data-upload operation completes.

UploadFileCompleted
UploadFileCompleted

Occurs when an asynchronous file-upload operation completes.

UploadProgressChanged
UploadProgressChanged

Occurs when an asynchronous upload operation successfully transfers some or all of the data.

UploadStringCompleted
UploadStringCompleted

Occurs when an asynchronous string-upload operation completes.

UploadValuesCompleted
UploadValuesCompleted

Occurs when an asynchronous upload of a name/value collection completes.

WriteStreamClosed
WriteStreamClosed

Occurs when an asynchronous operation to write data to a resource using a write stream is closed.

See Also
WebRequest WebRequest
WebResponse WebResponse
WebClient.AllowReadStreamBuffering WebClient.Allow
ReadStreamBuffering
I n this Article
Gets or sets a value that indicates whether to buffer the data read from the Internet resource for a WebClient instance.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public bool AllowReadStreamBuffering { get; set; }
member this.AllowReadStreamBuffering : bool with get, set

Returns
Boolean Boolean
true to enable buffering of the data received from the Internet resource; false to disable buffering. The default is
true .

Attributes ObsoleteAttribute

Remarks
When the AllowReadStreamBuffering property is true , the data is buffered in memory so it is ready to be read by the
app.
WebClient.AllowWriteStreamBuffering WebClient.Allow
WriteStreamBuffering
I n this Article
Gets or sets a value that indicates whether to buffer the data written to the Internet resource for a WebClient instance.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public bool AllowWriteStreamBuffering { get; set; }
member this.AllowWriteStreamBuffering : bool with get, set

Returns
Boolean Boolean
true to enable buffering of the data written to the Internet resource; false to disable buffering. The default is true .
Attributes ObsoleteAttribute

Remarks
When the AllowWriteStreamBuffering property is true , the data is buffered in memory so it can be written more
efficiently to the Internet resource in larger chunks.
WebClient.BaseAddress WebClient.BaseAddress
I n this Article
Gets or sets the base URI for requests made by a WebClient.
public string BaseAddress { get; set; }
member this.BaseAddress : string with get, set

Returns
String String
A String containing the base URI for requests made by a WebClient or Empty if no base address has been specified.
Exceptions
ArgumentException ArgumentException
BaseAddress is set to an invalid URI. The inner exception may contain information that will help you locate the error.

Examples
The following code example downloads data from an Internet server and displays it on the console. It assumes that the
server's address (such as http://www.contoso.com) is in hostUri and that the path to the resource (such as
/default.htm) is in uriSuffix .

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

// Set the BaseAddress of the Web Resource in the WebClient.


myWebClient.BaseAddress = hostUri;
Console.WriteLine("Downloading from " + hostUri + "/" + uriSuffix);
Console.WriteLine("
Press Enter key to continue");
Console.ReadLine();

// Download the target Web Resource into a byte array.


byte[] myDatabuffer = myWebClient.DownloadData (uriSuffix);

// Display the downloaded data.


string download = Encoding.ASCII.GetString(myDatabuffer);
Console.WriteLine(download);

Console.WriteLine("Download of " + myWebClient.BaseAddress.ToString() + uriSuffix + " was


successful.");

Remarks
The BaseAddress property contains a base URI that is combined with a relative address. When you call a method that
uploads or downloads data, the WebClient object combines this base URI with the relative address you specify in the
method call. If you specify an absolute URI, WebClient does not use the BaseAddress property value.
To remove a previously set value, set this property to null or an empty string ("").
WebClient.CachePolicy WebClient.CachePolicy
I n this Article
Gets or sets the application's cache policy for any resources obtained by this WebClient instance using WebRequest
objects.

public System.Net.Cache.RequestCachePolicy CachePolicy { get; set; }


member this.CachePolicy : System.Net.Cache.RequestCachePolicy with get, set

Returns
RequestCachePolicy RequestCachePolicy
A RequestCachePolicy object that represents the application's caching requirements.
WebClient.CancelAsync WebClient.CancelAsync
I n this Article
Cancels a pending asynchronous operation.
public void CancelAsync ();
member this.CancelAsync : unit -> unit

Remarks
If an operation is pending, this method calls Abort on the underlying WebRequest.
When you call CancelAsync, your application still receives the completion event associated with the operation. For
example, when you call CancelAsync to cancel a DownloadStringAsync operation, if you have specified an event
handler for the DownloadStringCompleted event, your event handler receives notification that the operation has
ended. To learn whether the operation completed successfully, check the Cancelled property on the base class of
DownloadDataCompletedEventArgs in the event data object passed to the event handler.
If no asynchronous operation is in progress, this method does nothing.
WebClient.Credentials WebClient.Credentials
I n this Article
Gets or sets the network credentials that are sent to the host and used to authenticate the request.
public System.Net.ICredentials Credentials { get; set; }
member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials containing the authentication credentials for the request. The default is null .

Examples
The following code example uses the user's system credentials to authenticate a request.
public static void Main()
{
try {

WebClient client = new WebClient();

client.Credentials = CredentialCache.DefaultCredentials;

Byte[] pageData = client.DownloadData("http://www.contoso.com");


string pageHtml = Encoding.ASCII.GetString(pageData);
Console.WriteLine(pageHtml);

} catch (WebException webEx) {


Console.Write(webEx.ToString());
}
}

Remarks
The Credentials property contains the authentication credentials used to access a resource on a host. In most client-
side scenarios, you should use the DefaultCredentials, which are the credentials of the currently logged on user. To do
this, set the UseDefaultCredentials property to true instead of setting this property.
If the WebClient class is being used in a middle tier application, such as an ASP.NET application, the DefaultCredentials
belong to the account running the ASP page (the server-side credentials). Typically, you would set this property to the
credentials of the client on whose behalf the request is made.
For security reasons, when automatically following redirects, store the credentials that you want to be included in the
redirect in a CredentialCache and assign it to this property. This property will automatically be set to null upon
redirection if it contains anything except a CredentialCache. Having this property value be automatically set to null
under those conditions prevents credentials from being sent to any unintended destination.
WebClient.DownloadData WebClient.DownloadData
I n this Article

Overloads
DownloadData(String) DownloadData(String)
Downloads the resource as a Byte array from the URI
specified.

DownloadData(Uri) DownloadData(Uri)
Downloads the resource as a Byte array from the URI
specified.

DownloadData(String) DownloadData(String)
Downloads the resource as a Byte array from the URI specified.
public byte[] DownloadData (string address);
member this.DownloadData : string -> byte[]

Parameters
address String String
The URI from which to download data.
Returns
Byte[]
A Byte array containing the downloaded resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading data.
NotSupportedException NotSupportedException
The method has been called simultaneously on multiple threads.
Examples
The following code example requests data from a server and displays the data returned. It assumes that remoteUri
contains a valid URI for the requested data.
Console.Write("
Please enter a URI (for example, http://www.contoso.com): ");
string remoteUri = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();
// Download home page data.
Console.WriteLine("Downloading " + remoteUri);
// Download the Web resource and save it into a data buffer.
byte[] myDataBuffer = myWebClient.DownloadData (remoteUri);

// Display the downloaded data.


string download = Encoding.ASCII.GetString(myDataBuffer);
Console.WriteLine(download);

Console.WriteLine("Download successful.");

Remarks
The DownloadData method downloads the resource with the URI specified by the address parameter. This method
blocks while downloading the resource. To download a resource and continue executing while waiting for the server's
response, use one of the DownloadDataAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

DownloadData(Uri) DownloadData(Uri)
Downloads the resource as a Byte array from the URI specified.
public byte[] DownloadData (Uri address);
member this.DownloadData : Uri -> byte[]

Parameters
address Uri Uri
The URI represented by the Uri object, from which to download data.
Returns
Byte[]
A Byte array containing the downloaded resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
Remarks
The DownloadData method downloads the resource with the URI specified by the address parameter. This method
blocks while downloading the resource. To download a resource and continue executing while waiting for the server's
response, use one of the DownloadDataAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note This member outputs trace information when you enable network tracing in your application. For more
information, see Network Tracing in the .NET Framework.
WebClient.DownloadDataAsync WebClient.Download
DataAsync
I n this Article

Overloads
DownloadDataAsync(Uri) DownloadDataAsync(Uri)
Downloads the resource as a Byte array from the URI specified
as an asynchronous operation.

DownloadDataAsync(Uri, Object) DownloadDataAsync(Uri,


Object) Downloads the resource as a Byte array from the URI specified
as an asynchronous operation.

DownloadDataAsync(Uri) DownloadDataAsync(Uri)
Downloads the resource as a Byte array from the URI specified as an asynchronous operation.
public void DownloadDataAsync (Uri address);
member this.DownloadDataAsync : Uri -> unit

Parameters
address Uri Uri
A Uri containing the URI to download.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
This method retrieves the specified resource using the default method for the protocol associated with the URI scheme
specified in address . The data is downloaded asynchronously using thread resources that are automatically allocated
from the thread pool.
This method does not block the calling thread while downloading the resource. To download a resource and block
while waiting for the server's response, use one of the DownloadData methods. When the download completes, the
DownloadDataCompleted event is raised. Your application must handle this event to receive notification. The
downloaded data is available in the Result property.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

DownloadDataAsync(Uri, Object) DownloadDataAsync(Uri, Object)


Downloads the resource as a Byte array from the URI specified as an asynchronous operation.
public void DownloadDataAsync (Uri address, object userToken);
member this.DownloadDataAsync : Uri * obj -> unit

Parameters
address Uri Uri
A Uri containing the URI to download.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
This method retrieves the specified resource using the default method for the protocol associated with the URI scheme
specified in address . The data is downloaded asynchronously using thread resources that are automatically allocated
from the thread pool.
This method does not block the calling thread while downloading the resource. To download a resource and block
while waiting for the server's response, use one of the DownloadData methods. When the download completes, the
DownloadDataCompleted event is raised. Your application must handle this event to receive notification. The
downloaded data is available in the Result property.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.DownloadDataCompleted WebClient.
DownloadDataCompleted
I n this Article
Occurs when an asynchronous data download operation completes.

public event System.Net.DownloadDataCompletedEventHandler DownloadDataCompleted;


member this.DownloadDataCompleted : System.Net.DownloadDataCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
// Sample call : DownLoadDataInBackground ("http://www.contoso.com/GameScores.html");
public static void DownloadDataInBackground (string address)
{
System.Threading.AutoResetEvent waiter = new System.Threading.AutoResetEvent (false);
WebClient client = new WebClient ();
Uri uri = new Uri(address);

// Specify that the DownloadDataCallback method gets called


// when the download completes.
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler (DownloadDataCallback);
client.DownloadDataAsync (uri, waiter);

// Block the main application thread. Real applications


// can perform other tasks while waiting for the download to complete.
waiter.WaitOne ();
}

Remarks
This event is raised each time an asynchronous data download operation completes. Asynchronous data downloads
are started by calling the DownloadDataAsync methods.
The DownloadDataCompletedEventHandler is the delegate for this event. The DownloadDataCompletedEventArgs
class provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.DownloadDataTaskAsync WebClient.
DownloadDataTaskAsync
I n this Article

Overloads
DownloadDataTaskAsync(String) DownloadDataTaskAsync(
String) Downloads the resource as a Byte array from the URI specified
as an asynchronous operation using a task object.

DownloadDataTaskAsync(Uri) DownloadDataTaskAsync(Uri)
Downloads the resource as a Byte array from the URI specified
as an asynchronous operation using a task object.

DownloadDataTaskAsync(String) DownloadDataTaskAsync(String)
Downloads the resource as a Byte array from the URI specified as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> DownloadDataTaskAsync (string address);
member this.DownloadDataTaskAsync : string -> System.Threading.Tasks.Task<byte[]>

Parameters
address String String
The URI of the resource to download.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the downloaded resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the data resource has been
downloaded.
This method retrieves the specified resource using the default method for the protocol associated with the URI scheme
specified in the address parameter. The data is downloaded asynchronously using thread resources that are
automatically allocated from the thread pool.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
The following code example requests data from a server and displays the data returned. It assumes that remoteUri
contains a valid URI for the requested data.

DownloadDataTaskAsync(Uri) DownloadDataTaskAsync(Uri)
Downloads the resource as a Byte array from the URI specified as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> DownloadDataTaskAsync (Uri address);
member this.DownloadDataTaskAsync : Uri -> System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to download.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the downloaded resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the data resource has been
downloaded.
This method retrieves the specified resource using the default method for the protocol associated with the URI scheme
specified in the address parameter. The data is downloaded asynchronously using thread resources that are
automatically allocated from the thread pool.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note This member outputs trace information when you enable network tracing in your application. For more
information, see Network Tracing in the .NET Framework.
WebClient.DownloadFile WebClient.DownloadFile
I n this Article

Overloads
DownloadFile(Uri, String) DownloadFile(Uri, String)
Downloads the resource with the specified URI to a local file.

DownloadFile(String, String) DownloadFile(String, String)


Downloads the resource with the specified URI to a local file.

DownloadFile(Uri, String) DownloadFile(Uri, String)


Downloads the resource with the specified URI to a local file.
public void DownloadFile (Uri address, string fileName);
member this.DownloadFile : Uri * string -> unit

Parameters
address Uri Uri
The URI specified as a String, from which to download data.
fileName String String
The name of the local file that is to receive the data.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
filename is null or Empty.
-or-
The file does not exist.
-or-
An error occurred while downloading data.
NotSupportedException NotSupportedException
The method has been called simultaneously on multiple threads.
Remarks
The DownloadFile method downloads to a local file data from the URI specified by in the address parameter. This
method blocks while downloading the resource. To download a resource and continue executing while waiting for the
server's response, use one of the DownloadFileAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
When using this method in a middle tier application, such as an ASP.NET page, you will receive an error if the account
under which the application executes does not have permission to access the file.

DownloadFile(String, String) DownloadFile(String, String)


Downloads the resource with the specified URI to a local file.

public void DownloadFile (string address, string fileName);


member this.DownloadFile : string * string -> unit

Parameters
address String String
The URI from which to download data.
fileName String String
The name of the local file that is to receive the data.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
filename is null or Empty.
-or-
The file does not exist.
-or- An error occurred while downloading data.
NotSupportedException NotSupportedException
The method has been called simultaneously on multiple threads.
Examples
The following code example downloads a file from http://www.contoso.com to the local hard drive.

string remoteUri = "http://www.contoso.com/library/homepage/images/";


string fileName = "ms-banner.gif", myStringWebResource = null;
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Concatenate the domain with the Web resource filename.
myStringWebResource = remoteUri + fileName;
Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......

", fileName, myStringWebResource);


// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile(myStringWebResource,fileName);
Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName,
myStringWebResource);
Console.WriteLine("
Downloaded file saved in the following file system folder:
" + Application.StartupPath);

Remarks
The DownloadFile method downloads to a local file data from the URI specified by in the address parameter. This
method blocks while downloading the resource. To download a resource and continue executing while waiting for the
server's response, use one of the DownloadFileAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
When using this method in a middle tier application, such as an ASP.NET page, you will receive an error if the account
under which the application executes does not have permission to access the file.
WebClient.DownloadFileAsync WebClient.DownloadFile
Async
I n this Article

Overloads
DownloadFileAsync(Uri, String) DownloadFileAsync(Uri, String)
Downloads, to a local file, the resource with the specified URI.
This method does not block the calling thread.

DownloadFileAsync(Uri, String, Object) DownloadFileAsync(Uri,


String, Object) Downloads, to a local file, the resource with the specified URI.
This method does not block the calling thread.

DownloadFileAsync(Uri, String) DownloadFileAsync(Uri, String)


Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.
public void DownloadFileAsync (Uri address, string fileName);
member this.DownloadFileAsync : Uri * string -> unit

Parameters
address Uri Uri
The URI of the resource to download.
fileName String String
The name of the file to be placed on the local computer.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
InvalidOperationException InvalidOperationException
The local file specified by fileName is in use by another thread.
Remarks
This method downloads the resource at the URI specified by in the address parameter. When the download completes
successfully, the downloaded file is named fileName on the local computer. The file is downloaded asynchronously
using thread resources that are automatically allocated from the thread pool. To receive notification when the file is
available, add an event handler to the DownloadFileCompleted event.
This method does not block the calling thread while the resource is being downloaded. To block while waiting for the
download to complete, use one of the DownloadFile methods.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
When using this method in an ASP.NET page, you will receive an error if the account that the page executes under
does not have permission to access the local file.

DownloadFileAsync(Uri, String, Object) DownloadFileAsync(Uri,


String, Object)
Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread.

public void DownloadFileAsync (Uri address, string fileName, object userToken);


member this.DownloadFileAsync : Uri * string * obj -> unit

Parameters
address Uri Uri
The URI of the resource to download.
fileName String String
The name of the file to be placed on the local computer.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
InvalidOperationException InvalidOperationException
The local file specified by fileName is in use by another thread.
Remarks
This method downloads the resource at the URI specified by in the address parameter. When the download completes
successfully, the downloaded file is named fileName on the local computer. The file is downloaded asynchronously
using thread resources that are automatically allocated from the thread pool. To receive notification when the file is
available, add an event handler to the DownloadFileCompleted event.
This method does not block the calling thread while the resource is being downloaded. To block while waiting for the
download to complete, use one of the DownloadFile methods.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
When using this method in an ASP.NET page, you will receive an error if the account that the page executes under
does not have permission to access the local file.
WebClient.DownloadFileCompleted WebClient.
DownloadFileCompleted
I n this Article
Occurs when an asynchronous file download operation completes.

public event System.ComponentModel.AsyncCompletedEventHandler DownloadFileCompleted;


member this.DownloadFileCompleted : System.ComponentModel.AsyncCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

// Specify that the DownloadFileCallback method gets called


// when the download completes.
client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
// Specify a progress notification handler.
client.DownloadProgressChanged += new
DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileAsync (uri, "serverdata.txt");
}

Remarks
This event is raised each time an asynchronous file download operation completes. Asynchronous file downloads are
started by calling the DownloadFileAsync methods.
The AsyncCompletedEventHandler is the delegate for this event. The AsyncCompletedEventArgs class provides the
event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.DownloadFileTaskAsync WebClient.Download
FileTaskAsync
I n this Article

Overloads
DownloadFileTaskAsync(String, String) DownloadFileTaskAsync(
String, String) Downloads the specified resource to a local file as an
asynchronous operation using a task object.

DownloadFileTaskAsync(Uri, String) DownloadFileTaskAsync(


Uri, String) Downloads the specified resource to a local file as an
asynchronous operation using a task object.

DownloadFileTaskAsync(String, String)
DownloadFileTaskAsync(String, String)
Downloads the specified resource to a local file as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task DownloadFileTaskAsync (string address, string fileName);
member this.DownloadFileTaskAsync : string * string -> System.Threading.Tasks.Task

Parameters
address String String
The URI of the resource to download.
fileName String String
The name of the file to be placed on the local computer.
Returns
Task Task
The task object representing the asynchronous operation.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
InvalidOperationException InvalidOperationException
The local file specified by fileName is in use by another thread.
Remarks
This operation will not block. The returned Task object will complete after the data resource has been downloaded.
This method downloads the resource at the URI specified by in the address parameter. When the download completes
successfully, the downloaded file is named fileName on the local computer. The file is downloaded asynchronously
using thread resources that are automatically allocated from the thread pool.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
When using this method in an ASP.NET page, you will receive an error if the account that the page executes under
does not have permission to access the local file.

DownloadFileTaskAsync(Uri, String) DownloadFileTaskAsync(Uri,


String)
Downloads the specified resource to a local file as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task DownloadFileTaskAsync (Uri address, string fileName);
member this.DownloadFileTaskAsync : Uri * string -> System.Threading.Tasks.Task

Parameters
address Uri Uri
The URI of the resource to download.
fileName String String
The name of the file to be placed on the local computer.
Returns
Task Task
The task object representing the asynchronous operation.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
InvalidOperationException InvalidOperationException
The local file specified by fileName is in use by another thread.
Remarks
This operation will not block. The returned Task object will complete after the data resource has been downloaded.
This method downloads the resource at the URI specified by in the address parameter. When the download completes
successfully, the downloaded file is named fileName on the local computer. The file is downloaded asynchronously
using thread resources that are automatically allocated from the thread pool.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
When using this method in an ASP.NET page, you will receive an error if the account that the page executes under
does not have permission to access the local file.
WebClient.DownloadProgressChanged WebClient.
DownloadProgressChanged
I n this Article
Occurs when an asynchronous download operation successfully transfers some or all of the data.

public event System.Net.DownloadProgressChangedEventHandler DownloadProgressChanged;


member this.DownloadProgressChanged : System.Net.DownloadProgressChangedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
// Sample call : DownLoadFileInBackground2 ("http://www.contoso.com/logs/January.txt");
public static void DownLoadFileInBackground2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

// Specify that the DownloadFileCallback method gets called


// when the download completes.
client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
// Specify a progress notification handler.
client.DownloadProgressChanged += new
DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileAsync (uri, "serverdata.txt");
}

The following code example shows an implementation of a handler for this event.
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} uploaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesSent,
e.TotalBytesToSend,
e.ProgressPercentage);
}
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}

Remarks
This event is raised each time an asynchronous download makes progress. This event is raised when downloads are
started using any of the following methods.
ME THO D D ES CR IPTIO N

DownloadDataAsync Downloads data from a resource and returns a Byte array,


without blocking the calling thread.

DownloadFileAsync Downloads data from a resource to a local file, without


blocking the calling thread.

OpenReadAsync Returns the data from a resource, without blocking the calling
thread.

The DownloadProgressChangedEventHandler is the delegate for this event. The


DownloadProgressChangedEventArgs class provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
Note

A passive FTP file transfer will always show a progress percentage of zero, since the server did not send the file size. To
show progress, you can change the FTP connection to active by overriding the GetWebRequest virtual method:

internal class MyWebClient : WebClient


{
protected override WebRequest GetWebRequest(Uri address)
{
FtpWebRequest req = (FtpWebRequest)base.GetWebRequest(address);
req.UsePassive = false;
return req;
}
}
WebClient.DownloadString WebClient.DownloadString
I n this Article

Overloads
DownloadString(String) DownloadString(String)
Downloads the requested resource as a String. The resource to
download is specified as a String containing the URI.

DownloadString(Uri) DownloadString(Uri)
Downloads the requested resource as a String. The resource to
download is specified as a Uri.

DownloadString(String) DownloadString(String)
Downloads the requested resource as a String. The resource to download is specified as a String containing the URI.
public string DownloadString (string address);
member this.DownloadString : string -> string

Parameters
address String String
A String containing the URI to download.
Returns
String String
A String containing the requested resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
NotSupportedException NotSupportedException
The method has been called simultaneously on multiple threads.
Examples
The following code example demonstrates calling this method.
public static void DownloadString (string address)
{
WebClient client = new WebClient ();
string reply = client.DownloadString (address);

Console.WriteLine (reply);
}

Remarks
This method retrieves the specified resource. After it downloads the resource, the method uses the encoding specified
in the Encoding property to convert the resource to a String. This method blocks while downloading the resource. To
download a resource and continue executing while waiting for the server's response, use one of the
DownloadStringAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

DownloadString(Uri) DownloadString(Uri)
Downloads the requested resource as a String. The resource to download is specified as a Uri.
public string DownloadString (Uri address);
member this.DownloadString : Uri -> string

Parameters
address Uri Uri
A Uri object containing the URI to download.
Returns
String String
A String containing the requested resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
NotSupportedException NotSupportedException
The method has been called simultaneously on multiple threads.
Remarks
This method retrieves the specified resource. After it downloads the resource, the method uses the encoding specified
in the Encoding property to convert the resource to a String. This method blocks while downloading the resource. To
download a resource and continue executing while waiting for the server's response, use one of the
DownloadStringAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.DownloadStringAsync WebClient.Download
StringAsync
I n this Article

Overloads
DownloadStringAsync(Uri) DownloadStringAsync(Uri)
Downloads the resource specified as a Uri. This method does
not block the calling thread.

DownloadStringAsync(Uri, Object) DownloadStringAsync(Uri,


Object) Downloads the specified string to the specified resource. This
method does not block the calling thread.

DownloadStringAsync(Uri) DownloadStringAsync(Uri)
Downloads the resource specified as a Uri. This method does not block the calling thread.
public void DownloadStringAsync (Uri address);
member this.DownloadStringAsync : Uri -> unit

Parameters
address Uri Uri
A Uri containing the URI to download.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
The resource is downloaded asynchronously using thread resources that are automatically allocated from the thread
pool.
After downloading the resource, this method uses the encoding specified in the Encoding property to convert the
resource to a String. This method does not block the calling thread while downloading the resource. To download a
resource and block while waiting for the server's response, use the DownloadString method. When the download
completes, the DownloadStringCompleted event is raised. Your application must handle this event to receive
notification. The downloaded string is available in the Result property.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

DownloadStringAsync(Uri, Object) DownloadStringAsync(Uri,


Object)
Downloads the specified string to the specified resource. This method does not block the calling thread.
public void DownloadStringAsync (Uri address, object userToken);
member this.DownloadStringAsync : Uri * obj -> unit

Parameters
address Uri Uri
A Uri containing the URI to download.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
The resource is downloaded asynchronously using thread resources that are automatically allocated from the thread
pool.
After downloading the resource, this method uses the encoding specified in the Encoding property to convert the
resource to a String. This method does not block the calling thread while downloading the resource. To download a
resource and block while waiting for the server's response, use the DownloadString method. When the download
completes, the DownloadStringCompleted event is raised. Your application must handle this event to receive
notification. The downloaded string is available in the Result property.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.DownloadStringCompleted WebClient.
DownloadStringCompleted
I n this Article
Occurs when an asynchronous resource-download operation completes.

public event System.Net.DownloadStringCompletedEventHandler DownloadStringCompleted;


member this.DownloadStringCompleted : System.Net.DownloadStringCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
// Sample call : DownloadStringInBackground2 ("http://www.contoso.com/GameScores.html");
public static void DownloadStringInBackground2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

// Specify that the DownloadStringCallback2 method gets called


// when the download completes.
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler
(DownloadStringCallback2);
client.DownloadStringAsync (uri);
}

Remarks
This event is raised each time an asynchronous operation to download a resource as a string completes. These
operations are started by calling the DownloadStringAsync methods.
The DownloadStringCompletedEventHandler is the delegate for this event. The DownloadStringCompletedEventArgs
class provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.DownloadStringTaskAsync WebClient.
DownloadStringTaskAsync
I n this Article

Overloads
DownloadStringTaskAsync(String) DownloadStringTaskAsync(
String) Downloads the resource as a String from the URI specified as
an asynchronous operation using a task object.

DownloadStringTaskAsync(Uri) DownloadStringTaskAsync(Uri)
Downloads the resource as a String from the URI specified as
an asynchronous operation using a task object.

DownloadStringTaskAsync(String)
DownloadStringTaskAsync(String)
Downloads the resource as a String from the URI specified as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<string> DownloadStringTaskAsync (string address);
member this.DownloadStringTaskAsync : string -> System.Threading.Tasks.Task<string>

Parameters
address String String
The URI of the resource to download.
Returns
Task<String>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the downloaded resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the data resource has been
downloaded. The resource is downloaded asynchronously using thread resources that are automatically allocated from
the thread pool.
After downloading the resource, this method uses the encoding specified in the Encoding property to convert the
resource to a String. This method does not block the calling thread while downloading the resource.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

DownloadStringTaskAsync(Uri) DownloadStringTaskAsync(Uri)
Downloads the resource as a String from the URI specified as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<string> DownloadStringTaskAsync (Uri address);
member this.DownloadStringTaskAsync : Uri -> System.Threading.Tasks.Task<string>

Parameters
address Uri Uri
The URI of the resource to download.
Returns
Task<String>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the downloaded resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the data resource has been
downloaded. The resource is downloaded asynchronously using thread resources that are automatically allocated from
the thread pool.
After downloading the resource, this method uses the encoding specified in the Encoding property to convert the
resource to a String. This method does not block the calling thread while downloading the resource.
You can use the CancelAsync method to cancel asynchronous operations that have not completed.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.Encoding WebClient.Encoding
I n this Article
Gets or sets the Encoding used to upload and download strings.
public System.Text.Encoding Encoding { get; set; }
member this.Encoding : System.Text.Encoding with get, set

Returns
Encoding Encoding
A Encoding that is used to encode strings. The default value of this property is the encoding returned by Default.

Examples
The following code example demonstrates setting the value of this property.
public static void UploadString (string address)
{
string data = "Time = 12:00am temperature = 50";
WebClient client = new WebClient ();
// Optionally specify an encoding for uploading and downloading strings.
client.Encoding = System.Text.Encoding.UTF8;
// Upload the data.
string reply = client.UploadString (address, data);
// Disply the server's response.
Console.WriteLine (reply);
}

Remarks
The UploadString and UploadStringAsync methods use this property to convert the specified string to a Byte array
before uploading the string. For additional information, see the GetBytes method.
When a string is downloaded using the DownloadString or DownloadStringAsync methods, WebClient uses the
Encoding returned by this to convert the downloaded Byte array into a string. For additional information, see the
GetString method.
WebClient.GetWebRequest WebClient.GetWebRequest
I n this Article
Returns a WebRequest object for the specified resource.
protected virtual System.Net.WebRequest GetWebRequest (Uri address);
abstract member GetWebRequest : Uri -> System.Net.WebRequest
override this.GetWebRequest : Uri -> System.Net.WebRequest

Parameters
address Uri Uri
A Uri that identifies the resource to request.
Returns
WebRequest WebRequest
A new WebRequest object for the specified resource.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override WebRequest GetWebRequest (Uri address)
{
WebRequest request = (WebRequest) base.GetWebRequest (address);

// Perform any customizations on the request.


// This version of WebClient always preauthenticates.
request.PreAuthenticate = true;
return request;
}

Remarks
This method copies the existing Headers, Credentials, and method to the newly created WebRequest object.
This method can be called only by classes that inherit from WebClient. It is provided to give inheritors access to the
underlying WebRequest object. Derived classes should call the base class implementation of GetWebRequest to ensure
the method works as expected.
WebClient.GetWebResponse WebClient.GetWeb
Response
I n this Article

Overloads
GetWebResponse(WebRequest) GetWebResponse(Web
Request) Returns the WebResponse for the specified WebRequest.

GetWebResponse(WebRequest, IAsyncResult) GetWeb


Response(WebRequest, IAsyncResult) Returns the WebResponse for the specified WebRequest using
the specified IAsyncResult.

GetWebResponse(WebRequest) GetWebResponse(WebRequest)
Returns the WebResponse for the specified WebRequest.
protected virtual System.Net.WebResponse GetWebResponse (System.Net.WebRequest request);
abstract member GetWebResponse : System.Net.WebRequest -> System.Net.WebResponse
override this.GetWebResponse : System.Net.WebRequest -> System.Net.WebResponse

Parameters
request WebRequest WebRequest
A WebRequest that is used to obtain the response.
Returns
WebResponse WebResponse
A WebResponse containing the response for the specified WebRequest.
Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override WebResponse GetWebResponse (WebRequest request)
{
WebResponse response = base.GetWebResponse (request);
// Perform any custom actions with the response ...
return response;
}

Remarks
The object returned by this method is obtained by calling the GetResponse method on the specified WebRequest
object.
This method can be called only by classes that inherit from WebClient. It is provided to give inheritors access to the
underlying WebResponse object.

GetWebResponse(WebRequest, IAsyncResult)
GetWebResponse(WebRequest, IAsyncResult)
Returns the WebResponse for the specified WebRequest using the specified IAsyncResult.
protected virtual System.Net.WebResponse GetWebResponse (System.Net.WebRequest request, IAsyncResult
result);
abstract member GetWebResponse : System.Net.WebRequest * IAsyncResult -> System.Net.WebResponse
override this.GetWebResponse : System.Net.WebRequest * IAsyncResult -> System.Net.WebResponse

Parameters
request WebRequest WebRequest
A WebRequest that is used to obtain the response.
result IAsyncResult IAsyncResult
An IAsyncResult object obtained from a previous call to BeginGetResponse(AsyncCallback, Object) .
Returns
WebResponse WebResponse
A WebResponse containing the response for the specified WebRequest.
Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.

protected override WebResponse GetWebResponse (WebRequest request, IAsyncResult result)


{
WebResponse response = base.GetWebResponse (request, result);
// Perform any custom actions with the response ...
return response;
}

Remarks
The object returned by this method is obtained by calling the EndGetResponse method on the specified WebRequest
object.
This method can be called only by classes that inherit from WebClient. It is provided to give inheritors access to the
underlying WebResponse object.
WebClient.Headers WebClient.Headers
I n this Article
Gets or sets a collection of header name/value pairs associated with the request.
public System.Net.WebHeaderCollection Headers { get; set; }
member this.Headers : System.Net.WebHeaderCollection with get, set

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection containing header name/value pairs associated with this request.

Examples
The following code example uses the Headers collection to set the HTTP Content-Type header to
application/x-www-form-urlencoded, to notify the server that form data is attached to the post.

string uriString;
Console.Write("
Please enter the URI to post data to {for example, http://www.contoso.com} : ");
uriString = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();
Console.WriteLine("
Please enter the data to be posted to the URI {0}:",uriString);
string postData = Console.ReadLine();
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

// Display the headers in the request


Console.Write("Resulting Request Headers: ");
Console.WriteLine(myWebClient.Headers.ToString());

// Apply ASCII Encoding to obtain the string as a byte array.

byte[] byteArray = Encoding.ASCII.GetBytes(postData);


Console.WriteLine("Uploading to {0} ...", uriString);
// Upload the input string using the HTTP 1.0 POST method.
byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);

// Decode and display the response.


Console.WriteLine("
Response received was {0}",
Encoding.ASCII.GetString(responseArray));

Remarks
The Headers property contains a WebHeaderCollection instance containing protocol headers that the WebClient sends
with the request.
Some common headers are considered restricted and are protected by the system and cannot be set or changed in a
WebHeaderCollection object. Any attempt to set one of these restricted headers in the WebHeaderCollection object
associated with a WebClient object will throw an exception later when attempting to send the WebClient request.
Restricted headers protected by the system include, but are not limited to the following:
Date
Host
In addition, some other headers are also restricted when using a WebClient object. These restricted headers include,
but are not limited to the following:
Accept
Connection
Content-Length
Expect (when the value is set to "100-continue"
If-Modified-Since
Range
Transfer-Encoding
The HttpWebRequest class has properties for setting some of the above headers. If it is important for an application to
set these headers, then the HttpWebRequest class should be used instead of the WebRequest class.
You should not assume that the header values will remain unchanged, because Web servers and caches may change or
add headers to a Web request.
WebClient.IsBusy WebClient.IsBusy
I n this Article
Gets whether a Web request is in progress.
public bool IsBusy { get; }
member this.IsBusy : bool

Returns
Boolean Boolean
true if the Web request is still in progress; otherwise false .
WebClient.OnDownloadDataCompleted WebClient.On
DownloadDataCompleted
I n this Article
Raises the DownloadDataCompleted event.

protected virtual void OnDownloadDataCompleted (System.Net.DownloadDataCompletedEventArgs e);


abstract member OnDownloadDataCompleted : System.Net.DownloadDataCompletedEventArgs -> unit
override this.OnDownloadDataCompleted : System.Net.DownloadDataCompletedEventArgs -> unit

Parameters
e DownloadDataCompletedEventArgs DownloadDataCompletedEventArgs
A DownloadDataCompletedEventArgs object that contains event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnDownloadDataCompleted (DownloadDataCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnDownloadDataCompleted(e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
DownloadDataCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events
The OnDownloadDataCompleted method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnDownloadFileCompleted WebClient.On
DownloadFileCompleted
I n this Article
Raises the DownloadFileCompleted event.

protected virtual void OnDownloadFileCompleted (System.ComponentModel.AsyncCompletedEventArgs e);


abstract member OnDownloadFileCompleted : System.ComponentModel.AsyncCompletedEventArgs -> unit
override this.OnDownloadFileCompleted : System.ComponentModel.AsyncCompletedEventArgs -> unit

Parameters
e AsyncCompletedEventArgs AsyncCompletedEventArgs
An AsyncCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnDownloadFileCompleted (System.ComponentModel.AsyncCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnDownloadFileCompleted(e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
DownloadFileCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnDownloadFileCompleted method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnDownloadProgressChanged WebClient.On
DownloadProgressChanged
I n this Article
Raises the DownloadProgressChanged event.

protected virtual void OnDownloadProgressChanged (System.Net.DownloadProgressChangedEventArgs e);


abstract member OnDownloadProgressChanged : System.Net.DownloadProgressChangedEventArgs -> unit
override this.OnDownloadProgressChanged : System.Net.DownloadProgressChangedEventArgs -> unit

Parameters
e DownloadProgressChangedEventArgs DownloadProgressChangedEventArgs
A DownloadProgressChangedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnDownloadProgressChanged (DownloadProgressChangedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnDownloadProgressChanged (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
DownloadProgressChanged event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnDownloadProgressChanged method also allows derived classes to handle the event without attaching a
delegate. This is the preferred technique for handling the event in a derived class.
WebClient.OnDownloadStringCompleted WebClient.On
DownloadStringCompleted
I n this Article
Raises the DownloadStringCompleted event.

protected virtual void OnDownloadStringCompleted (System.Net.DownloadStringCompletedEventArgs e);


abstract member OnDownloadStringCompleted : System.Net.DownloadStringCompletedEventArgs -> unit
override this.OnDownloadStringCompleted : System.Net.DownloadStringCompletedEventArgs -> unit

Parameters
e DownloadStringCompletedEventArgs DownloadStringCompletedEventArgs
A DownloadStringCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnDownloadStringCompleted (DownloadStringCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnDownloadStringCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
DownloadStringCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnDownloadStringCompleted method also allows derived classes to handle the event without attaching a
delegate. This is the preferred technique for handling the event in a derived class.
WebClient.OnOpenReadCompleted WebClient.OnOpen
ReadCompleted
I n this Article
Raises the OpenReadCompleted event.

protected virtual void OnOpenReadCompleted (System.Net.OpenReadCompletedEventArgs e);


abstract member OnOpenReadCompleted : System.Net.OpenReadCompletedEventArgs -> unit
override this.OnOpenReadCompleted : System.Net.OpenReadCompletedEventArgs -> unit

Parameters
e OpenReadCompletedEventArgs OpenReadCompletedEventArgs
A OpenReadCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnOpenReadCompleted (OpenReadCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnOpenReadCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
OpenReadCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnOpenReadCompleted method also allows derived classes to handle the event without attaching a delegate. This
is the preferred technique for handling the event in a derived class.
WebClient.OnOpenWriteCompleted WebClient.OnOpen
WriteCompleted
I n this Article
Raises the OpenWriteCompleted event.

protected virtual void OnOpenWriteCompleted (System.Net.OpenWriteCompletedEventArgs e);


abstract member OnOpenWriteCompleted : System.Net.OpenWriteCompletedEventArgs -> unit
override this.OnOpenWriteCompleted : System.Net.OpenWriteCompletedEventArgs -> unit

Parameters
e OpenWriteCompletedEventArgs OpenWriteCompletedEventArgs
A OpenWriteCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnOpenWriteCompleted (OpenWriteCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnOpenWriteCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
OpenWriteCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnOpenWriteCompleted method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnUploadDataCompleted WebClient.On
UploadDataCompleted
I n this Article
Raises the UploadDataCompleted event.

protected virtual void OnUploadDataCompleted (System.Net.UploadDataCompletedEventArgs e);


abstract member OnUploadDataCompleted : System.Net.UploadDataCompletedEventArgs -> unit
override this.OnUploadDataCompleted : System.Net.UploadDataCompletedEventArgs -> unit

Parameters
e UploadDataCompletedEventArgs UploadDataCompletedEventArgs
A UploadDataCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnUploadDataCompleted (UploadDataCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnUploadDataCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
UploadDataCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnUploadDataCompleted method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnUploadFileCompleted WebClient.On
UploadFileCompleted
I n this Article
Raises the UploadFileCompleted event.

protected virtual void OnUploadFileCompleted (System.Net.UploadFileCompletedEventArgs e);


abstract member OnUploadFileCompleted : System.Net.UploadFileCompletedEventArgs -> unit
override this.OnUploadFileCompleted : System.Net.UploadFileCompletedEventArgs -> unit

Parameters
e UploadFileCompletedEventArgs UploadFileCompletedEventArgs
An UploadFileCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnUploadFileCompleted (UploadFileCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnUploadFileCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
UploadFileCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnUploadFileCompleted method also allows derived classes to handle the event without attaching a delegate. This
is the preferred technique for handling the event in a derived class.
WebClient.OnUploadProgressChanged WebClient.On
UploadProgressChanged
I n this Article
Raises the UploadProgressChanged event.

protected virtual void OnUploadProgressChanged (System.Net.UploadProgressChangedEventArgs e);


abstract member OnUploadProgressChanged : System.Net.UploadProgressChangedEventArgs -> unit
override this.OnUploadProgressChanged : System.Net.UploadProgressChangedEventArgs -> unit

Parameters
e UploadProgressChangedEventArgs UploadProgressChangedEventArgs
An UploadProgressChangedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnUploadProgressChanged (UploadProgressChangedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnUploadProgressChanged (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
UploadProgressChanged event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnUploadProgressChanged method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnUploadStringCompleted WebClient.On
UploadStringCompleted
I n this Article
Raises the UploadStringCompleted event.

protected virtual void OnUploadStringCompleted (System.Net.UploadStringCompletedEventArgs e);


abstract member OnUploadStringCompleted : System.Net.UploadStringCompletedEventArgs -> unit
override this.OnUploadStringCompleted : System.Net.UploadStringCompletedEventArgs -> unit

Parameters
e UploadStringCompletedEventArgs UploadStringCompletedEventArgs
An UploadStringCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnUploadStringCompleted (UploadStringCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnUploadStringCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
UploadStringCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnUploadStringCompleted method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnUploadValuesCompleted WebClient.On
UploadValuesCompleted
I n this Article
Raises the UploadValuesCompleted event.

protected virtual void OnUploadValuesCompleted (System.Net.UploadValuesCompletedEventArgs e);


abstract member OnUploadValuesCompleted : System.Net.UploadValuesCompletedEventArgs -> unit
override this.OnUploadValuesCompleted : System.Net.UploadValuesCompletedEventArgs -> unit

Parameters
e UploadValuesCompletedEventArgs UploadValuesCompletedEventArgs
A UploadValuesCompletedEventArgs object containing event data.

Examples
The following code example shows an implementation of this method that can be customized by a class derived from
WebClient.
protected override void OnUploadValuesCompleted (UploadValuesCompletedEventArgs e)
{
// Here you can perform any custom actions before the event is raised
// and event handlers are called...

base.OnUploadValuesCompleted (e);

// Here you can perform any post event actions...


}

Remarks
Classes that inherit from this class can override this method to perform additional tasks when the
UploadValuesCompleted event occurs.
Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising
Events.
The OnUploadValuesCompleted method also allows derived classes to handle the event without attaching a delegate.
This is the preferred technique for handling the event in a derived class.
WebClient.OnWriteStreamClosed WebClient.OnWrite
StreamClosed
I n this Article
Raises the WriteStreamClosed event.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
protected virtual void OnWriteStreamClosed (System.Net.WriteStreamClosedEventArgs e);
abstract member OnWriteStreamClosed : System.Net.WriteStreamClosedEventArgs -> unit
override this.OnWriteStreamClosed : System.Net.WriteStreamClosedEventArgs -> unit

Parameters
e WriteStreamClosedEventArgs WriteStreamClosedEventArgs
A WriteStreamClosedEventArgs object containing event data.
Attributes ObsoleteAttribute
WebClient.OpenRead WebClient.OpenRead
I n this Article

Overloads
OpenRead(String) OpenRead(String)
Opens a readable stream for the data downloaded from a
resource with the URI specified as a String.

OpenRead(Uri) OpenRead(Uri)
Opens a readable stream for the data downloaded from a
resource with the URI specified as a Uri

OpenRead(String) OpenRead(String)
Opens a readable stream for the data downloaded from a resource with the URI specified as a String.
public System.IO.Stream OpenRead (string address);
member this.OpenRead : string -> System.IO.Stream

Parameters
address String String
The URI specified as a String from which to download data.
Returns
Stream Stream
A Stream used to read data from a resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress, address is invalid.
-or-
An error occurred while downloading data.
Examples
The following code example opens the resource identified by uriString and displays the results on the system
console. Note that the Stream returned by OpenRead is closed when the data has been read.
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Download home page data.
Console.WriteLine("Accessing {0} ...", uriString);
// Open a stream to point to the data stream coming from the Web resource.
Stream myStream = myWebClient.OpenRead(uriString);

Console.WriteLine("
Displaying Data :
");
StreamReader sr = new StreamReader(myStream);
Console.WriteLine(sr.ReadToEnd());

// Close the stream.


myStream.Close();

Remarks
The OpenRead method creates a Stream instance used to read the contents of the resource specified by the address
parameter. This method blocks while opening the stream. To continue executing while waiting for the stream, use one
of the OpenReadAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not null , it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

You must call Stream.Close when finished with the Stream to avoid running out of system resources.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenRead(Uri) OpenRead(Uri)
Opens a readable stream for the data downloaded from a resource with the URI specified as a Uri
public System.IO.Stream OpenRead (Uri address);
member this.OpenRead : Uri -> System.IO.Stream

Parameters
address Uri Uri
The URI specified as a Uri from which to download data.
Returns
Stream Stream
A Stream used to read data from a resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress, address is invalid.
-or-
An error occurred while downloading data.
Remarks
The OpenRead method creates a Stream instance used to read the contents of the resource specified by the address
parameter. This method blocks while opening the stream. To continue executing while waiting for the stream, use one
of the OpenReadAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not null , it is appended to address .

This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

You must call Stream.Close when finished with the Stream to avoid running out of system resources.
Note This member outputs trace information when you enable network tracing in your application. For more
information, see Network Tracing in the .NET Framework.
WebClient.OpenReadAsync WebClient.OpenReadAsync
I n this Article

Overloads
OpenReadAsync(Uri) OpenReadAsync(Uri)
Opens a readable stream containing the specified resource.
This method does not block the calling thread.

OpenReadAsync(Uri, Object) OpenReadAsync(Uri, Object)


Opens a readable stream containing the specified resource.
This method does not block the calling thread.

OpenReadAsync(Uri) OpenReadAsync(Uri)
Opens a readable stream containing the specified resource. This method does not block the calling thread.
public void OpenReadAsync (Uri address);
member this.OpenReadAsync : Uri -> unit

Parameters
address Uri Uri
The URI of the resource to retrieve.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
-or-
An error occurred while opening the stream.
Remarks
This method retrieves a Stream instance used to access the resource specified by the address parameter. The stream is
obtained using thread resources that are automatically allocated from the thread pool. To receive notification when the
stream is available, add an event handler to the OpenReadCompleted event.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
This method does not block the calling thread while the stream is opening. To block while waiting for the stream, use
the OpenReadAsync method.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested resource. If the
QueryString property is not null , it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenReadAsync(Uri, Object) OpenReadAsync(Uri, Object)


Opens a readable stream containing the specified resource. This method does not block the calling thread.
public void OpenReadAsync (Uri address, object userToken);
member this.OpenReadAsync : Uri * obj -> unit

Parameters
address Uri Uri
The URI of the resource to retrieve.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
-or-
An error occurred while opening the stream.
Remarks
This method retrieves a Stream instance used to access the resource specified by the address parameter. The stream is
obtained using thread resources that are automatically allocated from the thread pool. To receive notification when the
stream is available, add an event handler to the OpenReadCompleted event.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
This method does not block the calling thread while the stream is opening. To block while waiting for the stream, use
the OpenRead method.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested resource. If the
QueryString property is not null , it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.OpenReadCompleted WebClient.OpenRead
Completed
I n this Article
Occurs when an asynchronous operation to open a stream containing a resource completes.

public event System.Net.OpenReadCompletedEventHandler OpenReadCompleted;


member this.OpenReadCompleted : System.Net.OpenReadCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
public static void OpenResourceForReading2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

client.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCallback2);


client.OpenReadAsync (uri);
}

Remarks
This event is raised each time an asynchronous operation to open a stream containing a resource completes. These
operations are started by calling the OpenReadAsync methods.
The OpenReadCompletedEventHandler is the delegate for this event. The OpenReadCompletedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.OpenReadTaskAsync WebClient.OpenRead
TaskAsync
I n this Article

Overloads
OpenReadTaskAsync(String) OpenReadTaskAsync(String)
Opens a readable stream containing the specified resource as
an asynchronous operation using a task object.

OpenReadTaskAsync(Uri) OpenReadTaskAsync(Uri)
Opens a readable stream containing the specified resource as
an asynchronous operation using a task object.

OpenReadTaskAsync(String) OpenReadTaskAsync(String)
Opens a readable stream containing the specified resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<System.IO.Stream> OpenReadTaskAsync (string address);
member this.OpenReadTaskAsync : string -> System.Threading.Tasks.Task<System.IO.Stream>

Parameters
address String String
The URI of the resource to retrieve.
Returns
Task<Stream>
The task object representing the asynchronous operation. The Result property on the task object returns a Stream used
to read data from a resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
-or-
An error occurred while opening the stream.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a readable stream to the data
resource has been opened. This method does not block the calling thread while the stream is opening.
This method retrieves a Stream instance used to access the resource specified by the address parameter. The stream is
obtained using thread resources that are automatically allocated from the thread pool.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested resource. If the
QueryString property is not null , it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See StreamStream
Also

OpenReadTaskAsync(Uri) OpenReadTaskAsync(Uri)
Opens a readable stream containing the specified resource as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<System.IO.Stream> OpenReadTaskAsync (Uri address);
member this.OpenReadTaskAsync : Uri -> System.Threading.Tasks.Task<System.IO.Stream>

Parameters
address Uri Uri
The URI of the resource to retrieve.
Returns
Task<Stream>
The task object representing the asynchronous operation. The Result property on the task object returns a Stream used
to read data from a resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while downloading the resource.
-or-
An error occurred while opening the stream.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a readable stream to the data
resource has been opened. This method does not block the calling thread while the stream is opening.
This method retrieves a Stream instance used to access the resource specified by the address parameter. The stream is
obtained using thread resources that are automatically allocated from the thread pool.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested resource. If the
QueryString property is not null , it is appended to address .
This method uses the RETR command to download an FTP resource. For an HTTP resource, the GET method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See StreamStream
Also
WebClient.OpenWrite WebClient.OpenWrite
I n this Article

Overloads
OpenWrite(String) OpenWrite(String)
Opens a stream for writing data to the specified resource.

OpenWrite(Uri) OpenWrite(Uri)
Opens a stream for writing data to the specified resource.

OpenWrite(String, String) OpenWrite(String, String)


Opens a stream for writing data to the specified resource,
using the specified method.

OpenWrite(Uri, String) OpenWrite(Uri, String)


Opens a stream for writing data to the specified resource, by
using the specified method.

OpenWrite(String) OpenWrite(String)
Opens a stream for writing data to the specified resource.
public System.IO.Stream OpenWrite (string address);
member this.OpenWrite : string -> System.IO.Stream

Parameters
address String String
The URI of the resource to receive the data.
Returns
Stream Stream
A Stream used to write data to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
An error occurred while opening the stream.
Examples
The following code example reads data from the command line and uses OpenWrite to obtain a stream for writing the
data. Note that the Stream returned by OpenWrite is closed after the data is sent.
string uriString;
Console.Write("
Please enter the URI to post data to : ");
uriString = Console.ReadLine();
Console.WriteLine("
Please enter the data to be posted to the URI {0}:",uriString);
string postData = Console.ReadLine();
// Apply Ascii Encoding to obtain an array of bytes.
byte[] postArray = Encoding.ASCII.GetBytes(postData);

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

// postStream implicitly sets HTTP POST as the request method.


Console.WriteLine("Uploading to {0} ...", uriString); Stream postStream =
myWebClient.OpenWrite(uriString);

postStream.Write(postArray,0,postArray.Length);

// Close the stream and release resources.


postStream.Close();

Console.WriteLine("
Successfully posted the data.");

Remarks
The OpenWrite method returns a writable stream that is used to send data to a resource. This method blocks while
opening the stream. To continue executing while waiting for the stream, use one of the OpenWriteAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenWrite(Uri) OpenWrite(Uri)
Opens a stream for writing data to the specified resource.
public System.IO.Stream OpenWrite (Uri address);
member this.OpenWrite : Uri -> System.IO.Stream

Parameters
address Uri Uri
The URI of the resource to receive the data.
Returns
Stream Stream
A Stream used to write data to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
The OpenWrite method returns a writable stream that is used to send data to a resource. This method blocks while
opening the stream. To continue executing while waiting for the stream, use one of the OpenWriteAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenWrite(String, String) OpenWrite(String, String)


Opens a stream for writing data to the specified resource, using the specified method.

public System.IO.Stream OpenWrite (string address, string method);


member this.OpenWrite : string * string -> System.IO.Stream

Parameters
address String String
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
Returns
Stream Stream
A Stream used to write data to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
An error occurred while opening the stream.
Examples
The following code example reads data from the command line and uses OpenWrite to obtain a stream used to write
the data. Note that the Stream returned by OpenWrite must be closed to send the data.
string uriString;
Console.Write("
Please enter the URI to post data to : ");
uriString = Console.ReadLine();
Console.WriteLine("
Please enter the data to be posted to the URI {0}:",uriString);
string postData = Console.ReadLine();
// Apply ASCII encoding to obtain an array of bytes .
byte[] postArray = Encoding.ASCII.GetBytes(postData);

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

Console.WriteLine("Uploading to {0} ...", uriString);


Stream postStream = myWebClient.OpenWrite(uriString,"POST");
postStream.Write(postArray,0,postArray.Length);

// Close the stream and release resources.


postStream.Close();
Console.WriteLine("
Successfully posted the data.");

Remarks
The OpenWrite method returns a writable stream that is used to send data to a resource. The underlying request is
made with the method specified in the method parameter. The data is sent to the server when you close the stream.
This method blocks while opening the stream. To continue executing while waiting for the stream, use one of the
OpenWriteAsync methods.
If the method parameter specifies a method that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not specify an absolute address, address
must be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the
QueryString property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenWrite(Uri, String) OpenWrite(Uri, String)


Opens a stream for writing data to the specified resource, by using the specified method.
public System.IO.Stream OpenWrite (Uri address, string method);
member this.OpenWrite : Uri * string -> System.IO.Stream

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
Returns
Stream Stream
A Stream used to write data to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
The OpenWrite method returns a writable stream that is used to send data to a resource. This method blocks while
opening the stream. To continue executing while waiting for the stream, use one of the OpenWriteAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.OpenWriteAsync WebClient.OpenWriteAsync
I n this Article

Overloads
OpenWriteAsync(Uri, String, Object) OpenWriteAsync(Uri,
String, Object) Opens a stream for writing data to the specified resource,
using the specified method. This method does not block the
calling thread.

OpenWriteAsync(Uri, String) OpenWriteAsync(Uri, String)


Opens a stream for writing data to the specified resource. This
method does not block the calling thread.

OpenWriteAsync(Uri) OpenWriteAsync(Uri)
Opens a stream for writing data to the specified resource. This
method does not block the calling thread.

OpenWriteAsync(Uri, String, Object) OpenWriteAsync(Uri, String,


Object)
Opens a stream for writing data to the specified resource, using the specified method. This method does not block the
calling thread.
public void OpenWriteAsync (Uri address, string method, object userToken);
member this.OpenWriteAsync : Uri * string * obj -> unit

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
This method retrieves a writable stream that is used to send data to a resource. The stream is retrieved asynchronously
using thread resources that are automatically allocated from the thread pool. To receive notification when the stream is
available, add an event handler to the OpenWriteCompleted event. The contents of the stream are sent to the server
when you close the stream.
If the method parameter specifies a method that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
This method does not block the calling thread while the stream is being opened. To block while waiting for the stream,
use one of the OpenWrite methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenWriteAsync(Uri, String) OpenWriteAsync(Uri, String)


Opens a stream for writing data to the specified resource. This method does not block the calling thread.

public void OpenWriteAsync (Uri address, string method);


member this.OpenWriteAsync : Uri * string -> unit

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
Remarks
This method retrieves a writable stream that is used to send data to a resource. The stream is retrieved using thread
resources that are automatically allocated from the thread pool. To receive notification when the stream is available,
add an event handler to the OpenWriteCompleted event. When you close the stream, the thread blocks until the
request is sent to address and a response is received.
This method does not block the calling thread while the stream is being opened. To block while waiting for the stream,
use one of the OpenWrite methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenWriteAsync(Uri) OpenWriteAsync(Uri)
Opens a stream for writing data to the specified resource. This method does not block the calling thread.

public void OpenWriteAsync (Uri address);


member this.OpenWriteAsync : Uri -> unit

Parameters
address Uri Uri
The URI of the resource to receive the data.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
Remarks
This method retrieves a writable stream that is used to send data to a resource. The stream is retrieved using thread
resources that are automatically allocated from the thread pool. To receive notification when the stream is available,
add an event handler to the OpenWriteCompleted event. When you close the stream, the thread blocks until the
request is sent to address and a response is received.

This method does not block the calling thread while the stream is being opened. To block while waiting for the stream,
use one of the OpenWrite methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.OpenWriteCompleted WebClient.OpenWrite
Completed
I n this Article
Occurs when an asynchronous operation to open a stream to write data to a resource completes.

public event System.Net.OpenWriteCompletedEventHandler OpenWriteCompleted;


member this.OpenWriteCompleted : System.Net.OpenWriteCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
public static void OpenResourceForWriting2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

// Specify that the OpenWriteCallback method gets called


// when the writeable stream is available.
client.OpenWriteCompleted += new OpenWriteCompletedEventHandler (OpenWriteCallback2);
client.OpenWriteAsync (uri, "POST");
// Applications can perform other tasks
// while waiting for the upload to complete.
}

Remarks
This event is raised each time an asynchronous operation to open a stream that is used to send data to a resource
completes. These operations are started by calling the OpenWriteAsync methods.
The OpenWriteCompletedEventHandler is the delegate for this event. The OpenWriteCompletedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.OpenWriteTaskAsync WebClient.OpenWrite
TaskAsync
I n this Article

Overloads
OpenWriteTaskAsync(String) OpenWriteTaskAsync(String)
Opens a stream for writing data to the specified resource as
an asynchronous operation using a task object.

OpenWriteTaskAsync(Uri) OpenWriteTaskAsync(Uri)
Opens a stream for writing data to the specified resource as
an asynchronous operation using a task object.

OpenWriteTaskAsync(String, String) OpenWriteTaskAsync(


String, String) Opens a stream for writing data to the specified resource as
an asynchronous operation using a task object.

OpenWriteTaskAsync(Uri, String) OpenWriteTaskAsync(Uri,


String) Opens a stream for writing data to the specified resource as
an asynchronous operation using a task object.

OpenWriteTaskAsync(String) OpenWriteTaskAsync(String)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<System.IO.Stream> OpenWriteTaskAsync (string address);
member this.OpenWriteTaskAsync : string -> System.Threading.Tasks.Task<System.IO.Stream>

Parameters
address String String
The URI of the resource to receive the data.
Returns
Task<Stream>
The task object representing the asynchronous operation. The Result property on the task object returns a Stream used
to write data to the resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a writable stream to the data
resource has been opened. This method does not block the calling thread while the stream is opening.
This method retrieves a Stream instance used to write data to the resource specified by the address parameter. The
stream is obtained using thread resources that are automatically allocated from the thread pool.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See StreamStream
Also

OpenWriteTaskAsync(Uri) OpenWriteTaskAsync(Uri)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<System.IO.Stream> OpenWriteTaskAsync (Uri address);
member this.OpenWriteTaskAsync : Uri -> System.Threading.Tasks.Task<System.IO.Stream>

Parameters
address Uri Uri
The URI of the resource to receive the data.
Returns
Task<Stream>
The task object representing the asynchronous operation. The Result property on the task object returns a Stream used
to write data to the resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a writable stream to the data
resource has been opened. This method does not block the calling thread while the stream is opening.
This method retrieves a Stream instance used to write data to the resource specified by the address parameter. The
stream is obtained using thread resources that are automatically allocated from the thread pool.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

OpenWriteTaskAsync(String, String) OpenWriteTaskAsync(String,


String)
Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<System.IO.Stream> OpenWriteTaskAsync (string address, string
method);
member this.OpenWriteTaskAsync : string * string -> System.Threading.Tasks.Task<System.IO.Stream>

Parameters
address String String
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
Returns
Task<Stream>
The task object representing the asynchronous operation. The Result property on the task object returns a Stream used
to write data to the resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a writable stream to the data
resource has been opened. This method does not block the calling thread while the stream is opening.
This method retrieves a Stream instance used to write data to the resource specified by the address parameter. The
stream is obtained using thread resources that are automatically allocated from the thread pool.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
If the method parameter specifies a method that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See StreamStream
Also

OpenWriteTaskAsync(Uri, String) OpenWriteTaskAsync(Uri, String)


Opens a stream for writing data to the specified resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<System.IO.Stream> OpenWriteTaskAsync (Uri address, string
method);
member this.OpenWriteTaskAsync : Uri * string -> System.Threading.Tasks.Task<System.IO.Stream>

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
Returns
Task<Stream>
The task object representing the asynchronous operation. The Result property on the task object returns a Stream used
to write data to the resource.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a writable stream to the data
resource has been opened. This method does not block the calling thread while the stream is opening.
This method retrieves a Stream instance used to write data to the resource specified by the address parameter. The
stream is obtained using thread resources that are automatically allocated from the thread pool.
Note

You must call Stream.Close when you are finished with the Stream to avoid running out of system resources.
If the method parameter specifies a method that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See StreamStream
Also
WebClient.Proxy WebClient.Proxy
I n this Article
Gets or sets the proxy used by this WebClient object.
public System.Net.IWebProxy Proxy { get; set; }
member this.Proxy : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
An IWebProxy instance used to send requests.
Exceptions
ArgumentNullException ArgumentNullException
Proxy is set to null .

Remarks
The Proxy property identifies the IWebProxy instance that communicates with remote servers on behalf of this
WebClient object. The proxy is set by the system using configuration files and the Internet Explorer Local Area
Network settings. To specify that no proxy should be used, set the Proxy property to null .
For information on automatic proxy detection, see Automatic Proxy Detection.
See WebRequestWebRequest
Also WebResponseWebResponse
WebClient.QueryString WebClient.QueryString
I n this Article
Gets or sets a collection of query name/value pairs associated with the request.
public System.Collections.Specialized.NameValueCollection QueryString { get; set; }
member this.QueryString : System.Collections.Specialized.NameValueCollection with get, set

Returns
NameValueCollection NameValueCollection
A NameValueCollection that contains query name/value pairs associated with the request. If no pairs are associated
with the request, the value is an empty NameValueCollection.

Examples
The following code example takes user input from the command line and builds a NameValueCollection that is
assigned to the QueryString property. It then downloads the response from the server to a local file.
string uriString = "http://www.contoso.com/search";
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
// Create a new NameValueCollection instance to hold the QueryString parameters and values.
NameValueCollection myQueryStringCollection = new NameValueCollection();
Console.Write("Enter the word(s), separated by space character to search for in " + uriString + ":
");
// Read user input phrase to search for at uriString.
string searchPhrase = Console.ReadLine();
if (searchPhrase.Length > 1)
// Assign the user-defined search phrase.
myQueryStringCollection.Add("q",searchPhrase);
else
// If error, default to search for 'Microsoft'.
myQueryStringCollection.Add("q","Microsoft");
// Assign auxilliary parameters required for the search.
Console.WriteLine("Searching " + uriString + " .......");
// Attach QueryString to the WebClient.
myWebClient.QueryString = myQueryStringCollection;
// Download the search results Web page into 'searchresult.htm' for inspection.
myWebClient.DownloadFile (uriString, "searchresult.htm");
Console.WriteLine("
Download of " + uriString + " was successful. Please see 'searchresult.htm' for results.");

Remarks
The QueryString property contains a NameValueCollection instance containing name/value pairs that are appended to
the URI as a query string. The contents of the QueryString property are preceded by a question mark (?), and
name/value pairs are separated from one another by an ampersand (&).
WebClient.ResponseHeaders WebClient.Response
Headers
I n this Article
Gets a collection of header name/value pairs associated with the response.

public System.Net.WebHeaderCollection ResponseHeaders { get; }


member this.ResponseHeaders : System.Net.WebHeaderCollection

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection containing header name/value pairs associated with the response, or null if no response has
been received.

Examples
The following code example downloads and displays the ResponseHeaders returned by a server.
// Obtain the WebHeaderCollection instance containing the header name/value pair from the response.
WebHeaderCollection myWebHeaderCollection = myWebClient.ResponseHeaders;
Console.WriteLine("
Displaying the response headers
");
// Loop through the ResponseHeaders and display the header name/value pairs.
for (int i=0; i < myWebHeaderCollection.Count; i++)
Console.WriteLine (" " + myWebHeaderCollection.GetKey(i) + " = " +
myWebHeaderCollection.Get(i));

Remarks
The ResponseHeaders property contains a WebHeaderCollection instance containing header information the
WebClient receives with the response.
WebClient.UploadData WebClient.UploadData
I n this Article

Overloads
UploadData(String, Byte[]) UploadData(String, Byte[])
Uploads a data buffer to a resource identified by a URI.

UploadData(Uri, Byte[]) UploadData(Uri, Byte[])


Uploads a data buffer to a resource identified by a URI.

UploadData(String, String, Byte[]) UploadData(String, String,


Byte[]) Uploads a data buffer to the specified resource, using the
specified method.

UploadData(Uri, String, Byte[]) UploadData(Uri, String, Byte[])


Uploads a data buffer to the specified resource, using the
specified method.

UploadData(String, Byte[]) UploadData(String, Byte[])


Uploads a data buffer to a resource identified by a URI.
public byte[] UploadData (string address, byte[] data);
member this.UploadData : string * byte[] -> byte[]

Parameters
address String String
The URI of the resource to receive the data.
data Byte[]
The data buffer to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
An error occurred while sending the data.
-or-
There was no response from the server hosting the resource.
Examples
The following code example converts a string entered from the console to a Byte array and posts the array to the
specified server using UploadData. Any response from the server is displayed to the console.
Console.Write("
Please enter the URI to post data to : ");
string uriString = Console.ReadLine();
// Create a new WebClient instance.
WebClient myWebClient = new WebClient();
Console.WriteLine("
Please enter the data to be posted to the URI {0}:",uriString);
string postData = Console.ReadLine();
// Apply ASCII Encoding to obtain the string as a byte array.
byte[] postArray = Encoding.ASCII.GetBytes(postData);
Console.WriteLine("Uploading to {0} ...", uriString);
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

//UploadData implicitly sets HTTP POST as the request method.


byte[] responseArray = myWebClient.UploadData(uriString,postArray);

// Decode and display the response.


Console.WriteLine("
Response received was :{0}", Encoding.ASCII.GetString(responseArray));

Remarks
The UploadData method sends a data buffer to a resource.
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used. If
the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
The UploadData method sends the content of data to the server without encoding it. This method blocks while
uploading the data. To continue executing while waiting for the server's response, use one of the UploadDataAsync
methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadData(Uri, Byte[]) UploadData(Uri, Byte[])


Uploads a data buffer to a resource identified by a URI.

public byte[] UploadData (Uri address, byte[] data);


member this.UploadData : Uri * byte[] -> byte[]

Parameters
address Uri Uri
The URI of the resource to receive the data.
data Byte[]
The data buffer to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
An error occurred while sending the data.
-or-
There was no response from the server hosting the resource.
Remarks
The UploadData method sends a data buffer to a resource.
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used. If
the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
The UploadData method sends the content of data to the server without encoding it. This method blocks while
uploading the data. To continue executing while waiting for the server's response, use one of the UploadDataAsync
methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadData(String, String, Byte[]) UploadData(String, String,


Byte[])
Uploads a data buffer to the specified resource, using the specified method.
public byte[] UploadData (string address, string method, byte[] data);
member this.UploadData : string * string * byte[] -> byte[]

Parameters
address String String
The URI of the resource to receive the data.
method String String
The HTTP method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
data Byte[]
The data buffer to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
An error occurred while uploading the data.
-or-
There was no response from the server hosting the resource.
Examples
The following code example converts a string entered from the console into a byte array and posts the array to the
specified server using UploadData. Any response from the server is displayed to the console.
string uriString;
Console.Write("
Please enter the URI to post data to {for example, http://www.contoso.com} : ");
uriString = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();
Console.WriteLine("
Please enter the data to be posted to the URI {0}:",uriString);
string postData = Console.ReadLine();
myWebClient.Headers.Add("Content-Type","application/x-www-form-urlencoded");

// Display the headers in the request


Console.Write("Resulting Request Headers: ");
Console.WriteLine(myWebClient.Headers.ToString());

// Apply ASCII Encoding to obtain the string as a byte array.

byte[] byteArray = Encoding.ASCII.GetBytes(postData);


Console.WriteLine("Uploading to {0} ...", uriString);
// Upload the input string using the HTTP 1.0 POST method.
byte[] responseArray = myWebClient.UploadData(uriString,"POST",byteArray);

// Decode and display the response.


Console.WriteLine("
Response received was {0}",
Encoding.ASCII.GetString(responseArray));

Remarks
The UploadData method sends a data buffer to a resource using the HTTP method specified in the method parameter,
and returns any response from the server. This method blocks while uploading the data. To continue executing while
waiting for the server's response, use one of the UploadDataAsync methods.
The UploadData method sends the content of data to the server without encoding it.

If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadData(Uri, String, Byte[]) UploadData(Uri, String, Byte[])


Uploads a data buffer to the specified resource, using the specified method.

public byte[] UploadData (Uri address, string method, byte[] data);


member this.UploadData : Uri * string * byte[] -> byte[]

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The HTTP method used to send the data to the resource. If null, the default is POST for http and STOR for ftp.
data Byte[]
The data buffer to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
An error occurred while uploading the data.
-or-
There was no response from the server hosting the resource.
Remarks
The UploadData method sends a data buffer to a resource using the HTTP method specified in the method parameter,
and returns any response from the server. This method blocks while uploading the data. To continue executing while
waiting for the server's response, use one of the UploadDataAsync methods.
The UploadData method sends the content of data to the server without encoding it.

If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadDataAsync WebClient.UploadData
Async
I n this Article

Overloads
UploadDataAsync(Uri, String, Byte[]) UploadDataAsync(Uri,
String, Byte[]) Uploads a data buffer to a resource identified by a URI, using
the specified method. This method does not block the calling
thread.

UploadDataAsync(Uri, String, Byte[], Object) UploadData


Async(Uri, String, Byte[], Object) Uploads a data buffer to a resource identified by a URI, using
the specified method and identifying token.

UploadDataAsync(Uri, Byte[]) UploadDataAsync(Uri, Byte[])


Uploads a data buffer to a resource identified by a URI, using
the POST method. This method does not block the calling
thread.

UploadDataAsync(Uri, String, Byte[]) UploadDataAsync(Uri, String,


Byte[])
Uploads a data buffer to a resource identified by a URI, using the specified method. This method does not block the
calling thread.
public void UploadDataAsync (Uri address, string method, byte[] data);
member this.UploadDataAsync : Uri * string * byte[] -> unit

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.
data Byte[]
The data buffer to send to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded. To receive notification when the data upload
completes, add an event handler to the UploadDataCompleted event.
This method does not block the calling thread while the data is being sent. To send data and block while waiting for the
server's response, use one of the UploadData methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadDataAsync(Uri, String, Byte[], Object)


UploadDataAsync(Uri, String, Byte[], Object)
Uploads a data buffer to a resource identified by a URI, using the specified method and identifying token.

public void UploadDataAsync (Uri address, string method, byte[] data, object userToken);
member this.UploadDataAsync : Uri * string * byte[] * obj -> unit

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.

data Byte[]
The data buffer to send to the resource.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded. To receive notification when the data upload
completes, add an event handler to the UploadDataCompleted event.
This method does not block the calling thread while the data is being sent. To send data and block while waiting for the
server's response, use one of the UploadData methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadDataAsync(Uri, Byte[]) UploadDataAsync(Uri, Byte[])


Uploads a data buffer to a resource identified by a URI, using the POST method. This method does not block the
calling thread.
public void UploadDataAsync (Uri address, byte[] data);
member this.UploadDataAsync : Uri * byte[] -> unit

Parameters
address Uri Uri
The URI of the resource to receive the data.
data Byte[]
The data buffer to send to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded. To receive notification when the data upload
completes, add an event handler to the UploadDataCompleted event.
This method does not block the calling thread while the data is being sent. To send data and block while waiting for the
server's response, use one of the UploadData methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadDataCompleted WebClient.Upload
DataCompleted
I n this Article
Occurs when an asynchronous data-upload operation completes.

public event System.Net.UploadDataCompletedEventHandler UploadDataCompleted;


member this.UploadDataCompleted : System.Net.UploadDataCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
public static void UploadDataInBackground3 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);
string text = "Time = 12:00am temperature = 50";
byte[] data = System.Text.Encoding.UTF8.GetBytes (text);

client.UploadDataCompleted += new UploadDataCompletedEventHandler (UploadDataCallback3);


client.UploadDataAsync (uri, data);
}

Remarks
This event is raised each time an asynchronous data upload operation completes. Asynchronous data uploads are
started by calling the UploadDataAsync methods.
The UploadDataCompletedEventHandler is the delegate for this event. The UploadDataCompletedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.UploadDataTaskAsync WebClient.UploadData
TaskAsync
I n this Article

Overloads
UploadDataTaskAsync(String, Byte[]) UploadDataTaskAsync(
String, Byte[]) Uploads a data buffer that contains a Byte array to the URI
specified as an asynchronous operation using a task object.

UploadDataTaskAsync(Uri, Byte[]) UploadDataTaskAsync(Uri,


Byte[]) Uploads a data buffer that contains a Byte array to the URI
specified as an asynchronous operation using a task object.

UploadDataTaskAsync(String, String, Byte[]) UploadDataTask


Async(String, String, Byte[]) Uploads a data buffer that contains a Byte array to the URI
specified as an asynchronous operation using a task object.

UploadDataTaskAsync(Uri, String, Byte[]) UploadDataTask


Async(Uri, String, Byte[]) Uploads a data buffer that contains a Byte array to the URI
specified as an asynchronous operation using a task object.

UploadDataTaskAsync(String, Byte[])
UploadDataTaskAsync(String, Byte[])
Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadDataTaskAsync (string address, byte[] data);
member this.UploadDataTaskAsync : string * byte[] -> System.Threading.Tasks.Task<byte[]>

Parameters
address String String
The URI of the resource to receive the data.
data Byte[]
The data buffer to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the data buffer was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a data buffer has been
uploaded to the resource.
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadDataTaskAsync(Uri, Byte[]) UploadDataTaskAsync(Uri,


Byte[])
Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadDataTaskAsync (Uri address, byte[] data);
member this.UploadDataTaskAsync : Uri * byte[] -> System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to receive the data.
data Byte[]
The data buffer to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the data buffer was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a data buffer has been
uploaded to the resource.
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadDataTaskAsync(String, String, Byte[])


UploadDataTaskAsync(String, String, Byte[])
Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadDataTaskAsync (string address, string method,
byte[] data);
member this.UploadDataTaskAsync : string * string * byte[] -> System.Threading.Tasks.Task<byte[]>

Parameters
address String String
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.

data Byte[]
The data buffer to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the data buffer was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a data buffer has been
uploaded to the resource.
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadDataTaskAsync(Uri, String, Byte[])


UploadDataTaskAsync(Uri, String, Byte[])
Uploads a data buffer that contains a Byte array to the URI specified as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadDataTaskAsync (Uri address, string method, byte[]
data);
member this.UploadDataTaskAsync : Uri * string * byte[] -> System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to receive the data.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.

data Byte[]
The data buffer to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the data buffer was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the a data buffer has been
uploaded to the resource.
This method sends a data buffer to a resource. The data buffer is sent asynchronously using thread resources that are
automatically allocated from the thread pool. The data is not encoded.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadFile WebClient.UploadFile
I n this Article

Overloads
UploadFile(String, String) UploadFile(String, String)
Uploads the specified local file to a resource with the specified
URI.

UploadFile(Uri, String) UploadFile(Uri, String)


Uploads the specified local file to a resource with the specified
URI.

UploadFile(String, String, String) UploadFile(String, String,


String) Uploads the specified local file to the specified resource, using
the specified method.

UploadFile(Uri, String, String) UploadFile(Uri, String, String)


Uploads the specified local file to the specified resource, using
the specified method.

UploadFile(String, String) UploadFile(String, String)


Uploads the specified local file to a resource with the specified URI.
public byte[] UploadFile (string address, string fileName);
member this.UploadFile : string * string -> byte[]

Parameters
address String String
The URI of the resource to receive the file. For example, ftp://localhost/samplefile.txt.
fileName String String
The file to send to the resource. For example, "samplefile.txt".
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
fileName is null , is Empty, contains invalid characters, or does not exist.
-or-
An error occurred while uploading the file.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Examples
The following code example uploads the specified file to the specified URI using UploadFile. Any response returned by
the server is displayed on the console.

Console.Write("
Please enter the URI to post data to : ");
String uriString = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

Console.WriteLine("
Please enter the fully qualified path of the file to be uploaded to the URI");
string fileName = Console.ReadLine();
Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);

// Upload the file to the URI.


// The 'UploadFile(uriString,fileName)' method implicitly uses HTTP POST method.
byte[] responseArray = myWebClient.UploadFile(uriString,fileName);

// Decode and display the response.


Console.WriteLine("
Response Received.The contents of the file uploaded are:
{0}",
System.Text.Encoding.ASCII.GetString(responseArray));

The following code example shows an ASP.NET page that can accept posted files and is suitable for use with the
UploadFile method. The page must reside on a Web server. Its address provides the value for the address parameter
of the UploadFile method.
<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>


void Page_Load(object sender, EventArgs e) {

foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs("c:\\inetpub\ est\\UploadedFiles\\" + file.FileName);
}
}

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>

<%@ Import Namespace="System"%>


<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="VB" runat=server>


Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Dim f As String
Dim file
For Each f In Request.Files.AllKeys
file = Request.Files(f)
file.SaveAs("c:\inetpub est\UploadedFiles\" & file.FileName)
Next f

End Sub

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>

Remarks
The UploadFile method sends a local file to a resource. This method uses the STOR command to upload an FTP
resource. For an HTTP resource, the POST method is used.
This method blocks while uploading the file. To continue executing while waiting for the server's response, use one of
the UploadFileAsync methods.
The POST method is defined by HTTP. If the underlying request does not use HTTP and POST is not understood by the
server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the Status
property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFile(Uri, String) UploadFile(Uri, String)


Uploads the specified local file to a resource with the specified URI.
public byte[] UploadFile (Uri address, string fileName);
member this.UploadFile : Uri * string -> byte[]

Parameters
address Uri Uri
The URI of the resource to receive the file. For example, ftp://localhost/samplefile.txt.
fileName String String
The file to send to the resource. For example, "samplefile.txt".
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
fileName is null , is Empty, contains invalid characters, or does not exist.
-or-
An error occurred while uploading the file.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
The UploadFile method sends a local file to a resource. This method uses the STOR command to upload an FTP
resource. For an HTTP resource, the POST method is used.
This method blocks while uploading the file. To continue executing while waiting for the server's response, use one of
the UploadFileAsync methods.
The POST method is defined by HTTP. If the underlying request does not use HTTP and POST is not understood by the
server, the underlying protocol classes determine what occurs. Typically, a WebException is thrown with the Status
property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFile(String, String, String) UploadFile(String, String, String)


Uploads the specified local file to the specified resource, using the specified method.

public byte[] UploadFile (string address, string method, string fileName);


member this.UploadFile : string * string * string -> byte[]

Parameters
address String String
The URI of the resource to receive the file.
method String String
The method used to send the file to the resource. If null , the default is POST for http and STOR for ftp.

fileName String String


The file to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
fileName is null , is Empty, contains invalid characters, or does not exist.
-or-
An error occurred while uploading the file.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Examples
The following code example uploads the specified file to the specified URI using UploadFile. Any response returned by
the server is displayed on the console.

Console.Write("
Please enter the URL to post data to : ");
String uriString = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

Console.WriteLine("
Please enter the fully qualified path of the file to be uploaded to the URL");
string fileName = Console.ReadLine();

Console.WriteLine("Uploading {0} to {1} ...",fileName,uriString);


// Upload the file to the URL using the HTTP 1.0 POST.
byte[] responseArray = myWebClient.UploadFile(uriString,"POST",fileName);

// Decode and display the response.


Console.WriteLine("
Response Received.The contents of the file uploaded are:
{0}",
System.Text.Encoding.ASCII.GetString(responseArray));

The following code example shows an ASP.NET page that can accept posted files and is suitable for use with the
UploadFile method. The page must reside on a Web server. Its address provides the value for the address parameter
of the UploadFile method.

<%@ Import Namespace="System"%>


<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="C#" runat=server>


void Page_Load(object sender, EventArgs e) {

foreach(string f in Request.Files.AllKeys) {
HttpPostedFile file = Request.Files[f];
file.SaveAs("c:\\inetpub\ est\\UploadedFiles\\" + file.FileName);
}
}

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>
<%@ Import Namespace="System"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Net"%>
<%@ Import NameSpace="System.Web"%>

<Script language="VB" runat=server>


Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)

Dim f As String
Dim file
For Each f In Request.Files.AllKeys
file = Request.Files(f)
file.SaveAs("c:\inetpub est\UploadedFiles\" & file.FileName)
Next f

End Sub

</Script>
<html>
<body>
<p> Upload complete. </p>
</body>
</html>

Remarks
When address specifies an HTTP resource, the UploadFile method sends a local file to a resource using the HTTP
method specified in the method parameter and returns any response from the server. This method blocks while
uploading the file. To continue executing while waiting for the server's response, use one of the UploadFileAsync
methods.
If the method parameter specifies a verb that is not understood by the server or the address resource, the underlying
protocol classes determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the
error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFile(Uri, String, String) UploadFile(Uri, String, String)


Uploads the specified local file to the specified resource, using the specified method.

public byte[] UploadFile (Uri address, string method, string fileName);


member this.UploadFile : Uri * string * string -> byte[]

Parameters
address Uri Uri
The URI of the resource to receive the file.
method String String
The method used to send the file to the resource. If null , the default is POST for http and STOR for ftp.
fileName String String
The file to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
fileName is null , is Empty, contains invalid characters, or does not exist.
-or-
An error occurred while uploading the file.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
When address specifies an HTTP resource, the UploadFile method sends a local file to a resource using the HTTP
method specified in the method parameter and returns any response from the server. This method blocks while
uploading the file. To continue executing while waiting for the server's response, use one of the UploadFileAsync
methods.
If the method parameter specifies a verb that is not understood by the server or the address resource, the underlying
protocol classes determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the
error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadFileAsync WebClient.UploadFileAsync
I n this Article

Overloads
UploadFileAsync(Uri, String) UploadFileAsync(Uri, String)
Uploads the specified local file to the specified resource, using
the POST method. This method does not block the calling
thread.

UploadFileAsync(Uri, String, String) UploadFileAsync(Uri,


String, String) Uploads the specified local file to the specified resource, using
the POST method. This method does not block the calling
thread.

UploadFileAsync(Uri, String, String, Object) UploadFileAsync(


Uri, String, String, Object) Uploads the specified local file to the specified resource, using
the POST method. This method does not block the calling
thread.

UploadFileAsync(Uri, String) UploadFileAsync(Uri, String)


Uploads the specified local file to the specified resource, using the POST method. This method does not block the
calling thread.
public void UploadFileAsync (Uri address, string fileName);
member this.UploadFileAsync : Uri * string -> unit

Parameters
address Uri Uri
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
fileName String String
The file to send to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
The file is sent asynchronously using thread resources that are automatically allocated from the thread pool. To receive
notification when the file upload completes, add an event handler to the UploadFileCompleted event.
This method does not block the calling thread while the file is being sent. To send a file and block while waiting for the
server's response, use one of the UploadFile methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFileAsync(Uri, String, String) UploadFileAsync(Uri, String,


String)
Uploads the specified local file to the specified resource, using the POST method. This method does not block the
calling thread.

public void UploadFileAsync (Uri address, string method, string fileName);


member this.UploadFileAsync : Uri * string * string -> unit

Parameters
address Uri Uri
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.

fileName String String


The file to send to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
The file is sent asynchronously using thread resources that are automatically allocated from the thread pool. To receive
notification when the file upload completes, add an event handler to the UploadFileCompleted event.
This method does not block the calling thread while the file is being sent. To send a file and block while waiting for the
server's response, use one of the UploadFile methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFileAsync(Uri, String, String, Object) UploadFileAsync(Uri,


String, String, Object)
Uploads the specified local file to the specified resource, using the POST method. This method does not block the
calling thread.

public void UploadFileAsync (Uri address, string method, string fileName, object userToken);
member this.UploadFileAsync : Uri * string * string * obj -> unit

Parameters
address Uri Uri
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.

fileName String String


The file to send to the resource.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
The file is sent asynchronously using thread resources that are automatically allocated from the thread pool. To receive
notification when the file upload completes, add an event handler to the UploadFileCompleted event.
This method does not block the calling thread while the file is being sent. To send a file and block while waiting for the
server's response, use one of the UploadFile methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadFileCompleted WebClient.UploadFile
Completed
I n this Article
Occurs when an asynchronous file-upload operation completes.

public event System.Net.UploadFileCompletedEventHandler UploadFileCompleted;


member this.UploadFileCompleted : System.Net.UploadFileCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
// Sample call: UploadFileInBackground2("http://www.contoso.com/fileUpload.aspx", "data.txt")
public static void UploadFileInBackground2 (string address, string fileName)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

client.UploadFileCompleted += new UploadFileCompletedEventHandler (UploadFileCallback2);

// Specify a progress notification handler.


client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
client.UploadFileAsync (uri, "POST", fileName);
Console.WriteLine ("File upload started.");
}

Remarks
This event is raised each time an asynchronous file upload operation completes. Asynchronous file uploads are started
by calling the UploadFileAsync methods.
The UploadFileCompletedEventHandler is the delegate for this event. The UploadFileCompletedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.UploadFileTaskAsync WebClient.UploadFile
TaskAsync
I n this Article

Overloads
UploadFileTaskAsync(Uri, String, String) UploadFileTaskAsync(
Uri, String, String) Uploads the specified local file to a resource as an
asynchronous operation using a task object.

UploadFileTaskAsync(String, String, String) UploadFileTask


Async(String, String, String) Uploads the specified local file to a resource as an
asynchronous operation using a task object.

UploadFileTaskAsync(String, String) UploadFileTaskAsync(


String, String) Uploads the specified local file to a resource as an
asynchronous operation using a task object.

UploadFileTaskAsync(Uri, String) UploadFileTaskAsync(Uri,


String) Uploads the specified local file to a resource as an
asynchronous operation using a task object.

UploadFileTaskAsync(Uri, String, String) UploadFileTaskAsync(Uri,


String, String)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadFileTaskAsync (Uri address, string method, string
fileName);
member this.UploadFileTaskAsync : Uri * string * string -> System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.
fileName String String
The local file to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the file was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
This operation will not block. The returned Task<TResult> object will complete after the file has been uploaded to the
resource. The file is sent asynchronously using thread resources that are automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .

BY default, this method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method
is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFileTaskAsync(String, String, String)


UploadFileTaskAsync(String, String, String)
Uploads the specified local file to a resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadFileTaskAsync (string address, string method,
string fileName);
member this.UploadFileTaskAsync : string * string * string -> System.Threading.Tasks.Task<byte[]>
Parameters
address String String
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The method used to send the data to the resource. If null , the default is POST for http and STOR for ftp.

fileName String String


The local file to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the file was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
This operation will not block. The returned Task<TResult> object will complete after the file has been uploaded to the
resource. The file is sent asynchronously using thread resources that are automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .

BY default, this method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method
is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFileTaskAsync(String, String) UploadFileTaskAsync(String,


String)
Uploads the specified local file to a resource as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadFileTaskAsync (string address, string fileName);
member this.UploadFileTaskAsync : string * string -> System.Threading.Tasks.Task<byte[]>

Parameters
address String String
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
fileName String String
The local file to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the file was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
This operation will not block. The returned Task<TResult> object will complete after the file has been uploaded to the
resource. The file is sent asynchronously using thread resources that are automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadFileTaskAsync(Uri, String) UploadFileTaskAsync(Uri, String)


Uploads the specified local file to a resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadFileTaskAsync (Uri address, string fileName);
member this.UploadFileTaskAsync : Uri * string -> System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to receive the file. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
fileName String String
The local file to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the body of the response received from the resource when the file was uploaded.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The fileName parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
fileName is null , is Empty, contains invalid character, or the specified path to the file does not exist.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header begins with multipart .
Remarks
This operation will not block. The returned Task<TResult> object will complete after the file has been uploaded to the
resource. The file is sent asynchronously using thread resources that are automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string (""), address must be a relative URI that is combined with
BaseAddress to form the absolute URI of the requested data. If the QueryString property is not an empty string, it is
appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadProgressChanged WebClient.Upload
ProgressChanged
I n this Article
Occurs when an asynchronous upload operation successfully transfers some or all of the data.

public event System.Net.UploadProgressChangedEventHandler UploadProgressChanged;


member this.UploadProgressChanged : System.Net.UploadProgressChangedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
// Sample call: UploadFileInBackground2("http://www.contoso.com/fileUpload.aspx", "data.txt")
public static void UploadFileInBackground2 (string address, string fileName)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);

client.UploadFileCompleted += new UploadFileCompletedEventHandler (UploadFileCallback2);

// Specify a progress notification handler.


client.UploadProgressChanged += new UploadProgressChangedEventHandler(UploadProgressCallback);
client.UploadFileAsync (uri, "POST", fileName);
Console.WriteLine ("File upload started.");
}

The following code example shows an implementation of a handler for this event.
private static void UploadProgressCallback(object sender, UploadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} uploaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesSent,
e.TotalBytesToSend,
e.ProgressPercentage);
}
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}

Remarks
This event is raised each time an asynchronous upload makes progress. This event is raised when uploads are started
using any of the following methods.

ME THO D D ES CR IPTIO N
ME THO D D ES CR IPTIO N

UploadDataAsync Sends a Byte array to the resource, without blocking the


calling thread.

UploadFileAsync Sends a local file to the resource, without blocking the calling
thread.

UploadValuesAsync Sends a NameValueCollection to the resource and returns a


Byte array containing any response, without blocking the
calling thread.

The UploadProgressChangedEventHandler is the delegate for this event. The UploadProgressChangedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.UploadString WebClient.UploadString
I n this Article

Overloads
UploadString(String, String) UploadString(String, String)
Uploads the specified string to the specified resource, using
the POST method.

UploadString(Uri, String) UploadString(Uri, String)


Uploads the specified string to the specified resource, using
the POST method.

UploadString(String, String, String) UploadString(String, String,


String) Uploads the specified string to the specified resource, using
the specified method.

UploadString(Uri, String, String) UploadString(Uri, String,


String) Uploads the specified string to the specified resource, using
the specified method.

UploadString(String, String) UploadString(String, String)


Uploads the specified string to the specified resource, using the POST method.
public string UploadString (string address, string data);
member this.UploadString : string * string -> string

Parameters
address String String
The URI of the resource to receive the string. For Http resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
data String String
The string to be uploaded.
Returns
String String
A String containing the response sent by the server.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
Examples
The following code example demonstrates calling this method.
public static void UploadString (string address)
{
string data = "Time = 12:00am temperature = 50";
WebClient client = new WebClient ();
// Optionally specify an encoding for uploading and downloading strings.
client.Encoding = System.Text.Encoding.UTF8;
// Upload the data.
string reply = client.UploadString (address, data);
// Disply the server's response.
Console.WriteLine (reply);
}

Remarks
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted. To send a string and continue executing while waiting for
the server's response, use one of the UploadStringAsync methods.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadString(Uri, String) UploadString(Uri, String)


Uploads the specified string to the specified resource, using the POST method.

public string UploadString (Uri address, string data);


member this.UploadString : Uri * string -> string

Parameters
address Uri Uri
The URI of the resource to receive the string. For Http resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
data String String
The string to be uploaded.
Returns
String String
A String containing the response sent by the server.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
Remarks
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted. To send a string and continue executing while waiting for
the server's response, use one of the UploadStringAsync methods.
If the BaseAddress property is not an empty string (""), and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadString(String, String, String) UploadString(String, String,


String)
Uploads the specified string to the specified resource, using the specified method.

public string UploadString (string address, string method, string data);


member this.UploadString : string * string * string -> string

Parameters
address String String
The URI of the resource to receive the string. This URI must identify a resource that can accept a request sent with the
method method.

method String String


The HTTP method used to send the string to the resource. If null, the default is POST for http and STOR for ftp.
data String String
The string to be uploaded.
Returns
String String
A String containing the response sent by the server.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
-or-
method cannot be used to send content.
Examples
The following code example demonstrates calling this method.

public static void PostString (string address)


{
string data = "Time = 12:00am temperature = 50";
string method = "POST";
WebClient client = new WebClient ();
string reply = client.UploadString (address, method, data);

Console.WriteLine (reply);
}

Remarks
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted. To send a string and continue executing while waiting for
the server's response, use one of the UploadStringAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadString(Uri, String, String) UploadString(Uri, String, String)


Uploads the specified string to the specified resource, using the specified method.
public string UploadString (Uri address, string method, string data);
member this.UploadString : Uri * string * string -> string
Parameters
address Uri Uri
The URI of the resource to receive the string. This URI must identify a resource that can accept a request sent with the
method method.

method String String


The HTTP method used to send the string to the resource. If null, the default is POST for http and STOR for ftp.
data String String
The string to be uploaded.
Returns
String String
A String containing the response sent by the server.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
-or-
method cannot be used to send content.
Remarks
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted. To send a string and continue executing while waiting for
the server's response, use one of the UploadStringAsync methods.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadStringAsync WebClient.UploadString
Async
I n this Article

Overloads
UploadStringAsync(Uri, String) UploadStringAsync(Uri, String)
Uploads the specified string to the specified resource. This
method does not block the calling thread.

UploadStringAsync(Uri, String, String) UploadStringAsync(Uri,


String, String) Uploads the specified string to the specified resource. This
method does not block the calling thread.

UploadStringAsync(Uri, String, String, Object) UploadString


Async(Uri, String, String, Object) Uploads the specified string to the specified resource. This
method does not block the calling thread.

UploadStringAsync(Uri, String) UploadStringAsync(Uri, String)


Uploads the specified string to the specified resource. This method does not block the calling thread.
public void UploadStringAsync (Uri address, string data);
member this.UploadStringAsync : Uri * string -> unit

Parameters
address Uri Uri
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
data String String
The string to be uploaded.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a string to a resource. The string is sent asynchronously using thread resources that are
automatically allocated from the thread pool. Before uploading the string, this method converts it to a Byte array using
the encoding specified in the Encoding property. To receive notification when the string upload completes, you can add
an event handler to the UploadStringCompleted event.
This method does not block the calling thread while the string is being sent. To send a string and block while waiting
for the server's response, use one of the UploadString methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadStringAsync(Uri, String, String) UploadStringAsync(Uri,


String, String)
Uploads the specified string to the specified resource. This method does not block the calling thread.
public void UploadStringAsync (Uri address, string method, string data);
member this.UploadStringAsync : Uri * string * string -> unit

Parameters
address Uri Uri
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The HTTP method used to send the file to the resource. If null, the default is POST for http and STOR for ftp.
data String String
The string to be uploaded.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
method cannot be used to send content.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a string to a resource. The string is sent asynchronously using thread resources that are
automatically allocated from the thread pool. Before uploading the string, this method converts it to a Byte array using
the encoding specified in the Encoding property. To receive notification when the string upload completes, you can add
an event handler to the UploadStringCompleted event.
This method does not block the calling thread while the string is being sent. To send a string and block while waiting
for the server's response, use one of the UploadString methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadStringAsync(Uri, String, String, Object)


UploadStringAsync(Uri, String, String, Object)
Uploads the specified string to the specified resource. This method does not block the calling thread.

public void UploadStringAsync (Uri address, string method, string data, object userToken);
member this.UploadStringAsync : Uri * string * string * obj -> unit

Parameters
address Uri Uri
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The HTTP method used to send the file to the resource. If null, the default is POST for http and STOR for ftp.
data String String
The string to be uploaded.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
method cannot be used to send content.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a string to a resource. The string is sent asynchronously using thread resources that are
automatically allocated from the thread pool. Before uploading the string, this method converts it to a Byte array using
the encoding specified in the Encoding property. To receive notification when the string upload completes, you can add
an event handler to the UploadStringCompleted event.
This method does not block the calling thread while the string is being sent. To send a string and block while waiting
for the server's response, use one of the UploadString methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadStringCompleted WebClient.Upload
StringCompleted
I n this Article
Occurs when an asynchronous string-upload operation completes.

public event System.Net.UploadStringCompletedEventHandler UploadStringCompleted;


member this.UploadStringCompleted : System.Net.UploadStringCompletedEventHandler

Examples
The following code example demonstrates setting an event handler for this event.
public static void UploadStringInBackground2 (string address)
{
WebClient client = new WebClient ();
Uri uri = new Uri(address);
string data = "Time = 12:00am temperature = 50";
client.UploadStringCompleted += new UploadStringCompletedEventHandler (UploadStringCallback2);
client.UploadStringAsync (uri, data);
}

Remarks
This event is raised each time an asynchronous string upload operation completes. Asynchronous string uploads are
started by calling the UploadStringAsync methods.
The UploadStringCompletedEventHandler is the delegate for this event. The UploadStringCompletedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.UploadStringTaskAsync WebClient.Upload
StringTaskAsync
I n this Article

Overloads
UploadStringTaskAsync(Uri, String, String) UploadStringTask
Async(Uri, String, String) Uploads the specified string to the specified resource as an
asynchronous operation using a task object.

UploadStringTaskAsync(String, String, String) UploadStringTask


Async(String, String, String) Uploads the specified string to the specified resource as an
asynchronous operation using a task object.

UploadStringTaskAsync(String, String) UploadStringTaskAsync(


String, String) Uploads the specified string to the specified resource as an
asynchronous operation using a task object.

UploadStringTaskAsync(Uri, String) UploadStringTaskAsync(Uri,


String) Uploads the specified string to the specified resource as an
asynchronous operation using a task object.

UploadStringTaskAsync(Uri, String, String)


UploadStringTaskAsync(Uri, String, String)
Uploads the specified string to the specified resource as an asynchronous operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<string> UploadStringTaskAsync (Uri address, string method, string
data);
member this.UploadStringTaskAsync : Uri * string * string -> System.Threading.Tasks.Task<string>

Parameters
address Uri Uri
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The HTTP method used to send the file to the resource. If null, the default is POST for http and STOR for ftp.
data String String
The string to be uploaded.
Returns
Task<String>
The task object representing the asynchronous operation. The Result property on the task object returns a String
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
method cannot be used to send content.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the string has been uploaded to
the resource. The string is sent asynchronously using thread resources that are automatically allocated from the thread
pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadStringTaskAsync(String, String, String)


UploadStringTaskAsync(String, String, String)
Uploads the specified string to the specified resource as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<string> UploadStringTaskAsync (string address, string method,
string data);
member this.UploadStringTaskAsync : string * string * string -> System.Threading.Tasks.Task<string>

Parameters
address String String
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
method String String
The HTTP method used to send the file to the resource. If null, the default is POST for http and STOR for ftp.
data String String
The string to be uploaded.
Returns
Task<String>
The task object representing the asynchronous operation. The Result property on the task object returns a String
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
method cannot be used to send content.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the string has been uploaded to
the resource. The string is sent asynchronously using thread resources that are automatically allocated from the thread
pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadStringTaskAsync(String, String)
UploadStringTaskAsync(String, String)
Uploads the specified string to the specified resource as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<string> UploadStringTaskAsync (string address, string data);
member this.UploadStringTaskAsync : string * string -> System.Threading.Tasks.Task<string>

Parameters
address String String
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
data String String
The string to be uploaded.
Returns
Task<String>
The task object representing the asynchronous operation. The Result property on the task object returns a String
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the string has been uploaded to
the resource. The string is sent asynchronously using thread resources that are automatically allocated from the thread
pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
UploadStringTaskAsync(Uri, String) UploadStringTaskAsync(Uri,
String)
Uploads the specified string to the specified resource as an asynchronous operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<string> UploadStringTaskAsync (Uri address, string data);
member this.UploadStringTaskAsync : Uri * string -> System.Threading.Tasks.Task<string>

Parameters
address Uri Uri
The URI of the resource to receive the string. For HTTP resources, this URI must identify a resource that can accept a
request sent with the POST method, such as a script or ASP page.
data String String
The string to be uploaded.
Returns
Task<String>
The task object representing the asynchronous operation. The Result property on the task object returns a String
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
Remarks
This operation will not block. The returned Task<TResult> object will complete after the string has been uploaded to
the resource. The string is sent asynchronously using thread resources that are automatically allocated from the thread
pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
Before uploading the string, this method converts it to a Byte array using the encoding specified in the Encoding
property. This method blocks while the string is transmitted.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadValues WebClient.UploadValues
I n this Article

Overloads
UploadValues(String, NameValueCollection) UploadValues(
String, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI.

UploadValues(Uri, NameValueCollection) UploadValues(Uri,


NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI.

UploadValues(String, String, NameValueCollection) Upload


Values(String, String, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI, using the specified method.

UploadValues(Uri, String, NameValueCollection) UploadValues(


Uri, String, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI, using the specified method.

UploadValues(String, NameValueCollection) UploadValues(String,


NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI.
public byte[] UploadValues (string address, System.Collections.Specialized.NameValueCollection
data);
member this.UploadValues : string * System.Collections.Specialized.NameValueCollection -> byte[]

Parameters
address String String
The URI of the resource to receive the collection.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
There was no response from the server hosting the resource.
-or-
An error occurred while opening the stream.
-or-
The Content-type header is not null or "application/x-www -form-urlencoded".
Examples
The following code example gathers information from the user (name, age, and address) and posts the values to the
server using UploadValues. Any response from the server is displayed on the console.
Console.Write("
Please enter the URI to post data to : ");
string uriString = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
NameValueCollection myNameValueCollection = new NameValueCollection();

Console.WriteLine("Please enter the following parameters to be posted to the URL");


Console.Write("Name:");
string name = Console.ReadLine();

Console.Write("Age:");
string age = Console.ReadLine();

Console.Write("Address:");
string address = Console.ReadLine();

// Add necessary parameter/value pairs to the name/value container.


myNameValueCollection.Add("Name",name);
myNameValueCollection.Add("Address",address);
myNameValueCollection.Add("Age",age);

Console.WriteLine("
Uploading to {0} ...", uriString);
// 'The Upload(String,NameValueCollection)' implicitly method sets HTTP POST as the request method.
byte[] responseArray = myWebClient.UploadValues(uriString,myNameValueCollection);

// Decode and display the response.


Console.WriteLine("
Response received was :
{0}",Encoding.ASCII.GetString(responseArray));

Remarks
The UploadValues method sends a NameValueCollection to a server. This method blocks while uploading the data. To
continue executing while waiting for the server's response, use one of the UploadValuesAsync methods.
If the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
If the Content-type header is null , the UploadValues method sets it to "application/x-www -form-urlencoded".

If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValues(Uri, NameValueCollection) UploadValues(Uri,


NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI.
public byte[] UploadValues (Uri address, System.Collections.Specialized.NameValueCollection data);
member this.UploadValues : Uri * System.Collections.Specialized.NameValueCollection -> byte[]

Parameters
address Uri Uri
The URI of the resource to receive the collection.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
There was no response from the server hosting the resource.
-or-
An error occurred while opening the stream.
-or-
The Content-type header is not null or "application/x-www -form-urlencoded".
Remarks
The UploadValues method sends a NameValueCollection to a server. This method blocks while uploading the data. To
continue executing while waiting for the server's response, use one of the UploadValuesAsync methods.
If the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
If the Content-type header is null , the UploadValues method sets it to "application/x-www -form-urlencoded".

If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValues(String, String, NameValueCollection)


UploadValues(String, String, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI, using the specified method.

public byte[] UploadValues (string address, string method,


System.Collections.Specialized.NameValueCollection data);
member this.UploadValues : string * string * System.Collections.Specialized.NameValueCollection ->
byte[]

Parameters
address String String
The URI of the resource to receive the collection.
method String String
The HTTP method used to send the file to the resource. If null, the default is POST for http and STOR for ftp.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header value is not null and is not application/x-www-form-urlencoded .
Examples
The following code example gathers information from the user (name, age, and address) and posts the values to the
server using UploadValues. Any response from the server is displayed on the console.
Console.Write("
Please enter the URL to post data to : ");
string uriString = Console.ReadLine();

// Create a new WebClient instance.


WebClient myWebClient = new WebClient();

// Create a new NameValueCollection instance to hold some custom parameters to be posted to the URL.
NameValueCollection myNameValueCollection = new NameValueCollection();

Console.WriteLine("Please enter the following parameters to be posted to the URI");


Console.Write("Name:");
string name = Console.ReadLine();

Console.Write("Age:");
string age = Console.ReadLine();

Console.Write("Address:");
string address = Console.ReadLine();

// Add necessary parameter/value pairs to the name/value container.


myNameValueCollection.Add("Name",name);
myNameValueCollection.Add("Address",address);
myNameValueCollection.Add("Age",age);
Console.WriteLine("
Uploading to {0} ...", uriString);

// Upload the NameValueCollection.


byte[] responseArray = myWebClient.UploadValues(uriString,"POST",myNameValueCollection);

// Decode and display the response.


Console.WriteLine("
Response received was :
{0}",Encoding.ASCII.GetString(responseArray));

Remarks
The UploadValues method sends a NameValueCollection to a resource using the method specified in the method
parameter and returns any response from the server. This method blocks while uploading the data. To continue
executing while waiting for the server's response, use one of the UploadValuesAsync methods.
If the Content-type header is null , the UploadValues method sets it to application/x-www-form-urlencoded .

If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValues(Uri, String, NameValueCollection) UploadValues(Uri,


String, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI, using the specified method.
public byte[] UploadValues (Uri address, string method,
System.Collections.Specialized.NameValueCollection data);
member this.UploadValues : Uri * string * System.Collections.Specialized.NameValueCollection ->
byte[]

Parameters
address Uri Uri
The URI of the resource to receive the collection.
method String String
The HTTP method used to send the file to the resource. If null, the default is POST for http and STOR for ftp.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Byte[]
A Byte array containing the body of the response from the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
data is null .
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header value is not null and is not application/x-www-form-urlencoded .
Remarks
The UploadValues method sends a NameValueCollection to a resource using the method specified in the method
parameter and returns any response from the server. This method blocks while uploading the data. To continue
executing while waiting for the server's response, use one of the UploadValuesAsync methods.
If the Content-type header is null , the UploadValues method sets it to application/x-www-form-urlencoded .
If the method parameter specifies a verb that is not understood by the server, the underlying protocol classes
determine what occurs. Typically, a WebException is thrown with the Status property set to indicate the error.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UploadValuesAsync WebClient.UploadValues
Async
I n this Article

Overloads
UploadValuesAsync(Uri, NameValueCollection) UploadValues
Async(Uri, NameValueCollection) Uploads the data in the specified name/value collection to the
resource identified by the specified URI. This method does not
block the calling thread.

UploadValuesAsync(Uri, String, NameValueCollection) Upload


ValuesAsync(Uri, String, NameValueCollection) Uploads the data in the specified name/value collection to the
resource identified by the specified URI, using the specified
method. This method does not block the calling thread.

UploadValuesAsync(Uri, String, NameValueCollection, Object)


UploadValuesAsync(Uri, String, NameValueCollection, Object) Uploads the data in the specified name/value collection to the
resource identified by the specified URI, using the specified
method. This method does not block the calling thread, and
allows the caller to pass an object to the method that is
invoked when the operation completes.

UploadValuesAsync(Uri, NameValueCollection)
UploadValuesAsync(Uri, NameValueCollection)
Uploads the data in the specified name/value collection to the resource identified by the specified URI. This method
does not block the calling thread.
public void UploadValuesAsync (Uri address, System.Collections.Specialized.NameValueCollection
data);
member this.UploadValuesAsync : Uri * System.Collections.Specialized.NameValueCollection -> unit

Parameters
address Uri Uri
The URI of the resource to receive the collection. This URI must identify a resource that can accept a request sent with
the default method.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
Remarks
This method sends a string to a resource. The string is sent asynchronously using thread resources that are
automatically allocated from the thread pool. Before uploading the string, this method converts it to a Byte array using
the encoding specified in the Encoding property. To receive notification when the string upload completes, you can add
an event handler to the UploadStringCompleted event.
This method does not block the calling thread while the string is being sent. To send a string and block while waiting
for the server's response, use one of the UploadString methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValuesAsync(Uri, String, NameValueCollection)


UploadValuesAsync(Uri, String, NameValueCollection)
Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the
specified method. This method does not block the calling thread.
public void UploadValuesAsync (Uri address, string method,
System.Collections.Specialized.NameValueCollection data);
member this.UploadValuesAsync : Uri * string * System.Collections.Specialized.NameValueCollection ->
unit

Parameters
address Uri Uri
The URI of the resource to receive the collection. This URI must identify a resource that can accept a request sent with
the method method.
method String String
The method used to send the string to the resource. If null, the default is POST for http and STOR for ftp.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
-or-
method cannot be used to send content.
Remarks
This method sends the data contained in a NameValueCollection to the address resource. Use this method to send
form data to a URI for processing. The data is sent using the form-urlencoded media type; the Content-Type header
value must be set to "application/x-www -form-urlencoded". The header is set correctly by default. The
UploadValuesAsync methods throw a WebException if you call this method with a different Content-Type header value
set in the Headers collection.
If the method method is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
The NameValueCollection is sent asynchronously using thread resources that are automatically allocated from the
thread pool. To receive notification when the upload operation completes, add an event handler to the
UploadValuesCompleted event.
This method does not block the calling thread while the string is being sent. To send a string and block while waiting
for the server's response, use one of the UploadValues methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not empty, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information
see Network Tracing in the .NET Framework.

UploadValuesAsync(Uri, String, NameValueCollection, Object)


UploadValuesAsync(Uri, String, NameValueCollection, Object)
Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the
specified method. This method does not block the calling thread, and allows the caller to pass an object to the method
that is invoked when the operation completes.

public void UploadValuesAsync (Uri address, string method,


System.Collections.Specialized.NameValueCollection data, object userToken);
member this.UploadValuesAsync : Uri * string * System.Collections.Specialized.NameValueCollection *
obj -> unit

Parameters
address Uri Uri
The URI of the resource to receive the collection. This URI must identify a resource that can accept a request sent with
the method method.

method String String


The HTTP method used to send the string to the resource. If null, the default is POST for http and STOR for ftp.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
userToken Object Object
A user-defined object that is passed to the method invoked when the asynchronous operation completes.
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress and address is invalid.
-or-
There was no response from the server hosting the resource.
-or-
method cannot be used to send content.
Remarks
This method sends the data contained in a NameValueCollection to the address resource. Use this method to send
form data to a URI for processing. The data is sent using the form-urlencoded media type; the Content-Type header
value must be set to "application/x-www -form-urlencoded". The header is set correctly by default. The
UploadValuesAsync methods throw a WebException if you call this method with a different Content-Type header value
set in the Headers collection.
If the method method is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
The NameValueCollection is sent asynchronously using thread resources that are automatically allocated from the
thread pool. To receive notification when the upload operation completes, add an event handler to the
UploadValuesCompleted event.
This method does not block the calling thread while the string is being sent. To send a string and block while waiting
for the server's response, use one of the UploadValues methods.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not empty, it is appended to address .
Note

This member outputs trace information when you enable network tracing in your application. For more information
see Network Tracing in the .NET Framework.
WebClient.UploadValuesCompleted WebClient.Upload
ValuesCompleted
I n this Article
Occurs when an asynchronous upload of a name/value collection completes.

public event System.Net.UploadValuesCompletedEventHandler UploadValuesCompleted;


member this.UploadValuesCompleted : System.Net.UploadValuesCompletedEventHandler

Remarks
This event is raised each time an asynchronous upload of a NameValueCollection object's data completes. These
uploads are started by calling the UploadValuesAsync methods.
The UploadValuesCompletedEventHandler is the delegate for this event. The UploadValuesCompletedEventArgs class
provides the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebClient.UploadValuesTaskAsync WebClient.Upload
ValuesTaskAsync
I n this Article

Overloads
UploadValuesTaskAsync(String, String, NameValueCollection)
UploadValuesTaskAsync(String, String, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI as an asynchronous operation
using a task object.

UploadValuesTaskAsync(String, NameValueCollection) Upload


ValuesTaskAsync(String, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI as an asynchronous operation
using a task object.

UploadValuesTaskAsync(Uri, NameValueCollection) Upload


ValuesTaskAsync(Uri, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI as an asynchronous operation
using a task object.

UploadValuesTaskAsync(Uri, String, NameValueCollection)


UploadValuesTaskAsync(Uri, String, NameValueCollection) Uploads the specified name/value collection to the resource
identified by the specified URI as an asynchronous operation
using a task object.

UploadValuesTaskAsync(String, String, NameValueCollection)


UploadValuesTaskAsync(String, String, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadValuesTaskAsync (string address, string method,
System.Collections.Specialized.NameValueCollection data);
member this.UploadValuesTaskAsync : string * string *
System.Collections.Specialized.NameValueCollection -> System.Threading.Tasks.Task<byte[]>

Parameters
address String String
The URI of the resource to receive the collection.
method String String
The HTTP method used to send the collection to the resource. If null, the default is POST for http and STOR for ftp.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
method cannot be used to send content.
-or-
There was no response from the server hosting the resource.
-or-
An error occurred while opening the stream.
-or-
The Content-type header is not null or "application/x-www -form-urlencoded".
Remarks
This operation will not block. The returned Task<TResult> object will complete after the name/value collection has
been uploaded to the resource. The name/value collection is sent asynchronously using thread resources that are
automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
If the Content-type header is null , this method sets it to "application/x-www -form-urlencoded".
If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValuesTaskAsync(String, NameValueCollection)
UploadValuesTaskAsync(String, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.
[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadValuesTaskAsync (string address,
System.Collections.Specialized.NameValueCollection data);
member this.UploadValuesTaskAsync : string * System.Collections.Specialized.NameValueCollection ->
System.Threading.Tasks.Task<byte[]>

Parameters
address String String
The URI of the resource to receive the collection.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
There was no response from the server hosting the resource.
-or-
An error occurred while opening the stream.
-or-
The Content-type header is not null or "application/x-www -form-urlencoded".
Remarks
This operation will not block. The returned Task<TResult> object will complete after the name/value collection has
been uploaded to the resource. The name/value collection is sent asynchronously using thread resources that are
automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
If the Content-type header is null , this method sets it to "application/x-www -form-urlencoded".

If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .
This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValuesTaskAsync(Uri, NameValueCollection)
UploadValuesTaskAsync(Uri, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadValuesTaskAsync (Uri address,
System.Collections.Specialized.NameValueCollection data);
member this.UploadValuesTaskAsync : Uri * System.Collections.Specialized.NameValueCollection ->
System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to receive the collection.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .
WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
An error occurred while opening the stream.
-or-
There was no response from the server hosting the resource.
-or-
The Content-type header value is not null and is not application/x-www-form-urlencoded .
Remarks
This operation will not block. The returned Task<TResult> object will complete after the name/value collection has
been uploaded to the resource. The name/value collection is sent asynchronously using thread resources that are
automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
If the Content-type header is null , this method sets it to "application/x-www -form-urlencoded".

If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.

UploadValuesTaskAsync(Uri, String, NameValueCollection)


UploadValuesTaskAsync(Uri, String, NameValueCollection)
Uploads the specified name/value collection to the resource identified by the specified URI as an asynchronous
operation using a task object.

[System.Runtime.InteropServices.ComVisible(false)]
public System.Threading.Tasks.Task<byte[]> UploadValuesTaskAsync (Uri address, string method,
System.Collections.Specialized.NameValueCollection data);
member this.UploadValuesTaskAsync : Uri * string *
System.Collections.Specialized.NameValueCollection -> System.Threading.Tasks.Task<byte[]>

Parameters
address Uri Uri
The URI of the resource to receive the collection.
method String String
The HTTP method used to send the collection to the resource. If null, the default is POST for http and STOR for ftp.
data NameValueCollection NameValueCollection
The NameValueCollection to send to the resource.
Returns
Task<Byte[]>
The task object representing the asynchronous operation. The Result property on the task object returns a Byte array
containing the response sent by the server.
Attributes ComVisibleAttribute
Exceptions
ArgumentNullException ArgumentNullException
The address parameter is null .
-or-
The data parameter is null .

WebException WebException
The URI formed by combining BaseAddress, and address is invalid.
-or-
method cannot be used to send content.
-or-
There was no response from the server hosting the resource.
-or-
An error occurred while opening the stream.
-or-
The Content-type header is not null or "application/x-www -form-urlencoded".
Remarks
This operation will not block. The returned Task<TResult> object will complete after the name/value collection has
been uploaded to the resource. The name/value collection is sent asynchronously using thread resources that are
automatically allocated from the thread pool.
Asynchronous operations that have not completed can be canceled using the CancelAsync method.
If the underlying request is not understood by the server, the underlying protocol classes determine what occurs.
Typically, a WebException is thrown with the Status property set to indicate the error.
If the Content-type header is null , this method sets it to "application/x-www -form-urlencoded".

If the BaseAddress property is not an empty string ("") and address does not contain an absolute URI, address must
be a relative URI that is combined with BaseAddress to form the absolute URI of the requested data. If the QueryString
property is not an empty string, it is appended to address .

This method uses the STOR command to upload an FTP resource. For an HTTP resource, the POST method is used.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebClient.UseDefaultCredentials WebClient.UseDefault
Credentials
I n this Article
Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

public bool UseDefaultCredentials { get; set; }


member this.UseDefaultCredentials : bool with get, set

Returns
Boolean Boolean
true if the default credentials are used; otherwise false . The default value is false .

Examples
The following code example demonstrates setting this property.
// Sample call: UploadFileInBackground3("http://www.contoso.com/fileUpload.aspx", "data.txt")
public static void UploadFileInBackground3 (string address, string fileName)
{
WebClient client = new WebClient ();

Uri uri = new Uri(address);

client.UseDefaultCredentials = true;
client.UploadFileCompleted += new UploadFileCompletedEventHandler (UploadFileCallback2);
client.UploadFileAsync (uri, fileName);
Console.WriteLine ("File upload started.");
}

Remarks
Set this property to true when requests made by this WebClient object should, if requested by the server, be
authenticated using the default credentials of the currently logged on user. For client applications, this is the desired
behavior in most scenarios. For middle tier applications, such as ASP.NET applications, instead of using this property,
you would typically set the Credentials property to the credentials of the client on whose behalf the request is made.
WebClient
I n this Article
Initializes a new instance of the WebClient class.
public WebClient ();

Examples
The following code example creates a WebClient instance and then uses it to download data from a server and display
it on the system console, to download data from a server and write it to a file, and to upload form values to a server
and receive the response.
try {

// Download the data to a buffer.


WebClient client = new WebClient();

Byte[] pageData = client.DownloadData("http://www.contoso.com");


string pageHtml = Encoding.ASCII.GetString(pageData);
Console.WriteLine(pageHtml);

// Download the data to a file.


client.DownloadFile("http://www.contoso.com", "page.htm");

// Upload some form post values.


NameValueCollection form = new NameValueCollection();
form.Add("MyName", "MyValue");
Byte[] responseData = client.UploadValues("http://www.contoso.com/form.aspx", form);

}
catch (WebException webEx) {
Console.WriteLine(webEx.ToString());
if(webEx.Status == WebExceptionStatus.ConnectFailure) {
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}

Remarks
The default constructor creates a new instance of the WebClient class. The default HTTP method is GET. The default
FTP method is RETR. The default Encoding is Default. The default value of AllowAutoRedirect is true .
WebClient.WriteStreamClosed WebClient.WriteStream
Closed
I n this Article
Occurs when an asynchronous operation to write data to a resource using a write stream is closed.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public event System.Net.WriteStreamClosedEventHandler WriteStreamClosed;
member this.WriteStreamClosed : System.Net.WriteStreamClosedEventHandler

Attributes ObsoleteAttribute

Remarks
This event is raised each time an asynchronous operation used to write data to a resource using a write stream is
closed. These operations result from calls to the OpenWriteTaskAsync methods.
The WriteStreamClosedEventHandler is the delegate for this event. The WriteStreamClosedEventArgs class provides
the event handler with event data.
For more information about how to handle events, see Handling and Raising Events.
WebException WebException Class
The exception that is thrown when an error occurs while accessing the network through a pluggable protocol.

D eclaration
[System.Serializable]
public class WebException : InvalidOperationException
type WebException = class
inherit InvalidOperationException
interface ISerializable

I nheritance H ierarchy
Object Object
Exception Exception
SystemException SystemException
InvalidOperationException InvalidOperationException

Remarks
The WebException class is thrown by classes descended from WebRequest and WebResponse that implement
pluggable protocols for accessing the Internet.
When WebException is thrown by a descendant of the WebRequest class, the Response property provides the Internet
response to the application.
Associated Tips
Check the Response property of the exception to determine why the request failed.
When a WebException exception is thrown by a descendent of the WebRequest class, the Response property provides
the Internet response to the application.
Check the Status property of the exception to determine why the request failed.
The Status property of the exception provides status information for the error. For more information, see
WebExceptionStatus.
If you are timing out when stepping into an XML Web Service, set the timeout value for the XML Web
Service call to infinite.
For more information, see Error: Timeout While Debugging Web Services.

Constructors
WebException()
WebException()

Initializes a new instance of the WebException class.

WebException(String)
WebException(String)

Initializes a new instance of the WebException class with the specified error message.
WebException(SerializationInfo, StreamingContext)
WebException(SerializationInfo, StreamingContext)

Initializes a new instance of the WebException class from the specified SerializationInfo and StreamingContext
instances.

WebException(String, WebExceptionStatus)
WebException(String, WebExceptionStatus)

Initializes a new instance of the WebException class with the specified error message and status.

WebException(String, Exception)
WebException(String, Exception)

Initializes a new instance of the WebException class with the specified error message and nested exception.

WebException(String, Exception, WebExceptionStatus, WebResponse)


WebException(String, Exception, WebExceptionStatus, WebResponse)

Initializes a new instance of the WebException class with the specified error message, nested exception, status, and
response.

Properties
Response
Response

Gets the response that the remote host returned.

Status
Status

Gets the status of the response.

Methods
GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo instance with the data needed to serialize the WebException.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Serializes this instance into the specified SerializationInfo object.


See Also
Exception Exception
WebException.GetObjectData WebException.GetObject
Data
I n this Article
Populates a SerializationInfo instance with the data needed to serialize the WebException.

public override void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to be used.
streamingContext StreamingContext StreamingContext
The StreamingContext to be used.
WebException.ISerializable.GetObjectData
I n this Article
Serializes this instance into the specified SerializationInfo object.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The object into which this WebException will be serialized.
streamingContext StreamingContext
The destination of the serialization.
WebException.Response WebException.Response
I n this Article
Gets the response that the remote host returned.
public System.Net.WebResponse Response { get; }
member this.Response : System.Net.WebResponse

Returns
WebResponse WebResponse
If a response is available from the Internet resource, a WebResponse instance that contains the error response from an
Internet resource; otherwise, null .

Examples
The following example checks the Status property and prints to the console the StatusCode and StatusDescription of
the underlying HttpWebResponse instance.
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create
call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");

// Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"

Exception Message :" + e.Message);


if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}",
((HttpWebResponse)e.Response).StatusDescription);
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}

Remarks
Some Internet protocols, such as HTTP, return otherwise valid responses indicating that an error has occurred at the
protocol level. When the response to an Internet request indicates an error, WebRequest.GetResponse sets the Status
property to WebExceptionStatus.ProtocolError and provides the WebResponse that contains the error message in the
Response property of the WebException that was thrown. The application can examine the WebResponse to determine
the actual error.
WebException.Status WebException.Status
I n this Article
Gets the status of the response.
public System.Net.WebExceptionStatus Status { get; }
member this.Status : System.Net.WebExceptionStatus

Returns
WebExceptionStatus WebExceptionStatus
One of the WebExceptionStatus values.

Examples
The following example checks the Status property and prints to the console the StatusCode and StatusDescription of
the underlying HttpWebResponse instance.
try {
// Create a web request for an invalid site. Substitute the "invalid site" strong in the Create
call with a invalid name.
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("invalid site");

// Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("This program is expected to throw WebException on successful run."+
"

Exception Message :" + e.Message);


if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}",
((HttpWebResponse)e.Response).StatusDescription);
}
}
catch(Exception e) {
Console.WriteLine(e.Message);
}

Remarks
The Status property indicates the reason for the WebException.
The value of Status is one of the WebExceptionStatus values.
W arning

The ProxyNameResolutionFailure error is not returned to Windows 8.x Store apps.


See WebExceptionStatusWebExceptionStatus
Also
WebException WebException
I n this Article

Overloads
WebException()
Initializes a new instance of the WebException class.

WebException(String) WebException(String)
Initializes a new instance of the WebException class with the
specified error message.

WebException(SerializationInfo, StreamingContext) Web


Exception(SerializationInfo, StreamingContext) Initializes a new instance of the WebException class from the
specified SerializationInfo and StreamingContext instances.

WebException(String, WebExceptionStatus) WebException(


String, WebExceptionStatus) Initializes a new instance of the WebException class with the
specified error message and status.

WebException(String, Exception) WebException(String,


Exception) Initializes a new instance of the WebException class with the
specified error message and nested exception.

WebException(String, Exception, WebExceptionStatus, Web


Response) WebException(String, Exception, WebException Initializes a new instance of the WebException class with the
Status, WebResponse) specified error message, nested exception, status, and
response.

WebException()
Initializes a new instance of the WebException class.

public WebException ();

Examples
The following example throws a default WebException.
try
{
// A 'Socket' object has been created.
Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method.

IPHostEntry hostEntry = Dns.Resolve("http://www.contoso.com");

IPAddress serverAddress = hostEntry.AddressList[0];


IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
httpSocket.Connect(endPoint);
Console.WriteLine("Connection created successfully");
httpSocket.Close();
}
catch(SocketException e)
{
String exp = e.Message;
// Throw the WebException with no parameters.
throw new WebException();
}

Remarks
The default constructor initializes a new instance of the WebException class. The Message property is initialized to a
system-supplied message that describes the error. This message takes into account the current system culture. The
InnerException and Response properties are initialized to null . The Status property is initialized to RequestCanceled.

WebException(String) WebException(String)
Initializes a new instance of the WebException class with the specified error message.
public WebException (string message);
new System.Net.WebException : string -> System.Net.WebException

Parameters
message String String
The text of the error message.
Examples
The following example throws a WebException by specifying an error message.
try
{
// A 'Socket' object has been created.
Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

// The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method.
IPHostEntry hostEntry = Dns.Resolve(connectUri);

IPAddress serverAddress = hostEntry.AddressList[0];


IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
httpSocket.Connect(endPoint);
Console.WriteLine("Connection created successfully");
httpSocket.Close();
}
catch(SocketException e)
{
Console.WriteLine("
Exception thrown.
The Original Message is: "+e.Message);
// Throw the 'WebException' object with a message string specific to the situation.
throw new WebException("Unable to locate the Server with 'www.contoso.com' Uri.");
}

Remarks
The WebException instance is initialized with the Message property set to the value of message . If message is null ,
the Message property is initialized to a system-supplied message. The InnerException and Response properties are
initialized to null . The Status property is initialized to RequestCanceled.
See ExceptionException
Also

WebException(SerializationInfo, StreamingContext)
WebException(SerializationInfo, StreamingContext)
Initializes a new instance of the WebException class from the specified SerializationInfo and StreamingContext
instances.

protected WebException (System.Runtime.Serialization.SerializationInfo serializationInfo,


System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.WebException : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.WebException

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo that contains the information required to serialize the new WebException.
streamingContext StreamingContext StreamingContext
A StreamingContext that contains the source of the serialized stream that is associated with the new WebException.
Remarks
This constructor implements the ISerializable interface for the WebException class.
See ISerializableISerializable
Also
WebException(String, WebExceptionStatus) WebException(String,
WebExceptionStatus)
Initializes a new instance of the WebException class with the specified error message and status.

public WebException (string message, System.Net.WebExceptionStatus status);


new System.Net.WebException : string * System.Net.WebExceptionStatus -> System.Net.WebException

Parameters
message String String
The text of the error message.
status WebExceptionStatus WebExceptionStatus
One of the WebExceptionStatus values.
Examples
The following example throws a WebException by specifying an error message and a WebExceptionStatus.

try
{
// A 'Socket' object has been created.
Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);

// The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method.

IPHostEntry hostEntry = Dns.Resolve("http://www.contoso.com");

IPAddress serverAddress = hostEntry.AddressList[0];


IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
httpSocket.Connect(endPoint);
Console.WriteLine("Connection created successfully");
httpSocket.Close();

}
catch(SocketException e)
{
Console.WriteLine("
Exception thrown.
The Original Message is: "+e.Message);
// Throw the 'WebException' object with a message string and message status specific to the
situation.
throw new WebException("Unable to locate the Server with 'www.contoso.com'
Uri.",WebExceptionStatus.NameResolutionFailure);
}

Remarks
The WebException instance is initialized with the Message property set to the value of message and the Status
property set to the value of status . If message is null , the Message property is initialized to a system-supplied
message. The InnerException and Response properties are initialized to null .

WebException(String, Exception) WebException(String, Exception)


Initializes a new instance of the WebException class with the specified error message and nested exception.
public WebException (string message, Exception innerException);
new System.Net.WebException : string * Exception -> System.Net.WebException

Parameters
message String String
The text of the error message.
inner Exception Exception
A nested exception.
Examples
The following example throws a WebException by specifying an error message and nested exception.

try
{
// A 'Socket' object has been created.
Socket httpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);

// The IPaddress of the unknown uri is resolved using the 'Dns.Resolve' method.

IPHostEntry hostEntry = Dns.Resolve(connectUri);

IPAddress serverAddress = hostEntry.AddressList[0];


IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);
httpSocket.Connect(endPoint);
Console.WriteLine("Connection created successfully");
httpSocket.Close();
}
catch(SocketException e)
{
Console.WriteLine("
Exception thrown.
The Original Message is: "+e.Message);
// Throw the 'WebException' object with a message string specific to the situation;
// and the 'InnerException' which actually lead to this exception.
throw new WebException("Unable to locate the Server with 'www.contoso.com' Uri.",e);
}

Remarks
The WebException instance is initialized with the Message property set to the value of message and the InnerException
property set to the value of innerException . If message is null , the Message property is initialized to a system-
supplied message. The InnerException and Response properties are initialized to null . The Status property is
initialized to RequestCanceled.
See ExceptionException
Also

WebException(String, Exception, WebExceptionStatus,


WebResponse) WebException(String, Exception,
WebExceptionStatus, WebResponse)
Initializes a new instance of the WebException class with the specified error message, nested exception, status, and
response.

public WebException (string message, Exception innerException, System.Net.WebExceptionStatus status,


System.Net.WebResponse response);
new System.Net.WebException : string * Exception * System.Net.WebExceptionStatus *
System.Net.WebResponse -> System.Net.WebException

Parameters
message String String
The text of the error message.
inner Exception Exception
A nested exception.
status WebExceptionStatus WebExceptionStatus
One of the WebExceptionStatus values.
response WebResponse WebResponse
A WebResponse instance that contains the response from the remote host.
Examples
The following example throws a WebException by specifying an error message and a WebExceptionStatus.
// Send the data.
Encoding ASCII = Encoding.ASCII;
string requestPage = "GET /nhjj.htm HTTP/1.1\r
Host: " + connectUri + "\r
Connection: Close\r
\r
";
Byte[] byteGet = ASCII.GetBytes(requestPage);
Byte[] recvBytes = new Byte[256];

// Create an 'IPEndPoint' object.

IPHostEntry hostEntry = Dns.Resolve(connectUri);


IPAddress serverAddress = hostEntry.AddressList[0];
IPEndPoint endPoint = new IPEndPoint(serverAddress, 80);

// Create a 'Socket' object for sending data.


Socket connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);

// Connect to host using 'IPEndPoint' object.

connectSocket.Connect(endPoint);

// Sent the 'requestPage' text to the host.


connectSocket.Send(byteGet, byteGet.Length, 0);

// Receive the information sent by the server.


Int32 bytesReceived = connectSocket.Receive(recvBytes, recvBytes.Length, 0);
String headerString = ASCII.GetString(recvBytes, 0, bytesReceived);

// Check whether 'status 404' is there or not in the information sent by server.
if(headerString.IndexOf("404")!=-1)
{
bytesReceived = connectSocket.Receive(recvBytes, recvBytes.Length, 0);
MemoryStream memoryStream = new MemoryStream(recvBytes);
getStream = (Stream) memoryStream;

// Create a 'WebResponse' object


WebResponse myWebResponse = (WebResponse) new HttpConnect(getStream);
Exception myException = new Exception("File Not found");

// Throw the 'WebException' object with a message string, message status,InnerException and
WebResponse
throw new WebException("The Requested page is not
found.",myException,WebExceptionStatus.ProtocolError,myWebResponse);

connectSocket.Close();

Remarks
The WebException instance is initialized with the Message property set to the value of message , the InnerException
property set to the value of innerException , the Status property set to the value of status , and the Response
property set to the value of response . If message is null , the Message property is initialized to a system-supplied
message.
WebExceptionStatus WebExceptionStatus Enum
Defines status codes for the WebException class.

D eclaration
public enum WebExceptionStatus
type WebExceptionStatus =

I nheritance H ierarchy
Object Object
ValueType ValueType
Enum Enum

Remarks
The WebExceptionStatus enumeration defines the status codes assigned to the Status property.

Fields
CacheEntryNotFound The specified cache entry was not found.
CacheEntryNotFound

ConnectFailure ConnectFailure The remote service point could not be contacted at the transport level.

ConnectionClosed The connection was prematurely closed.


ConnectionClosed

KeepAliveFailure The connection for a request that specifies the Keep-alive header was closed
KeepAliveFailure unexpectedly.

MessageLengthLimitExceeded A message was received that exceeded the specified limit when sending a request or
MessageLengthLimitExceeded receiving a response from the server.

NameResolutionFailure The name resolver service could not resolve the host name.
NameResolutionFailure

Pending Pending An internal asynchronous request is pending.

PipelineFailure The request was a pipelined request and the connection was closed before the
PipelineFailure response was received.
ProtocolError ProtocolError The response received from the server was complete but indicated a protocol-level
error. For example, an HTTP protocol error such as 401 Access Denied would use this
status.

ProxyNameResolutionFailure The name resolver service could not resolve the proxy host name.
ProxyNameResolutionFailure

ReceiveFailure ReceiveFailure A complete response was not received from the remote server.

RequestCanceled The request was canceled, the Abort() method was called, or an unclassifiable error
RequestCanceled occurred. This is the default value for Status.

RequestProhibitedByCachePolicy The request was not permitted by the cache policy. In general, this occurs when a
RequestProhibitedByCachePolicy request is not cacheable and the effective policy prohibits sending the request to the
server. You might receive this status if a request method implies the presence of a
request body, a request method requires direct interaction with the server, or a
request contains a conditional header.

RequestProhibitedByProxy This request was not permitted by the proxy.


RequestProhibitedByProxy

SecureChannelFailure An error occurred while establishing a connection using SSL.


SecureChannelFailure

SendFailure SendFailure A complete request could not be sent to the remote server.

ServerProtocolViolation The server response was not a valid HTTP response.


ServerProtocolViolation

Success Success No error was encountered.

Timeout Timeout No response was received during the time-out period for a request.

TrustFailure TrustFailure A server certificate could not be validated.

UnknownError UnknownError An exception of unknown type has occurred.

See Also
WebHeaderCollection WebHeaderCollection Class
Contains protocol headers associated with a request or response.

D eclaration
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class WebHeaderCollection : System.Collections.Specialized.NameValueCollection,
System.Runtime.Serialization.ISerializable
type WebHeaderCollection = class
inherit NameValueCollection
interface ISerializable

I nheritance H ierarchy
Object Object
NameObjectCollectionBase NameObjectCollectionBase
NameValueCollection NameValueCollection

Remarks
The WebHeaderCollection class is generally accessed through WebRequest.Headers or WebResponse.Headers. Some
common headers are considered restricted and are either exposed directly by the API (such as Content-Type ) or
protected by the system and cannot be changed.
The restricted headers are:
Accept
Connection
Content-Length
Content-Type
Date
Expect
Host
If-Modified-Since
Range
Referer
Transfer-Encoding
User-Agent
Proxy-Connection

Constructors
WebHeaderCollection()
WebHeaderCollection()
Initializes a new instance of the WebHeaderCollection class.

WebHeaderCollection(SerializationInfo, StreamingContext)
WebHeaderCollection(SerializationInfo, StreamingContext)

Initializes a new instance of the WebHeaderCollection class from the specified instances of the SerializationInfo
and StreamingContext classes.

Properties
AllKeys
AllKeys

Gets all header names (keys) in the collection.

Count
Count

Gets the number of headers in the collection.

Item[HttpRequestHeader]
Item[HttpRequestHeader]

Gets or sets the specified request header.

Item[HttpResponseHeader]
Item[HttpResponseHeader]

Gets or sets the specified response header.

Item[String]
Item[String]

Keys
Keys

Gets the collection of header names (keys) in the collection.

Methods
Add(String)
Add(String)

Inserts the specified header into the collection.


Add(HttpRequestHeader, String)
Add(HttpRequestHeader, String)

Inserts the specified header with the specified value into the collection.

Add(HttpResponseHeader, String)
Add(HttpResponseHeader, String)

Inserts the specified header with the specified value into the collection.

Add(String, String)
Add(String, String)

Inserts a header with the specified name and value into the collection.

AddWithoutValidate(String, String)
AddWithoutValidate(String, String)

Inserts a header into the collection without checking whether the header is on the restricted header list.

Clear()
Clear()

Removes all headers from the collection.

Get(Int32)
Get(Int32)

Gets the value of a particular header in the collection, specified by an index into the collection.

Get(String)
Get(String)

Gets the value of a particular header in the collection, specified by the name of the header.

GetEnumerator()
GetEnumerator()

Returns an enumerator that can iterate through the WebHeaderCollection instance.

GetKey(Int32)
GetKey(Int32)

Gets the header name at the specified position in the collection.


GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

GetValues(String)
GetValues(String)

Gets an array of header values stored in a header.

GetValues(Int32)
GetValues(Int32)

Gets an array of header values stored in the index position of the header collection.

IsRestricted(String)
IsRestricted(String)

Tests whether the specified HTTP header can be set for the request.

IsRestricted(String, Boolean)
IsRestricted(String, Boolean)

Tests whether the specified HTTP header can be set for the request or the response.

OnDeserialization(Object)
OnDeserialization(Object)

Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

Remove(HttpRequestHeader)
Remove(HttpRequestHeader)

Removes the specified header from the collection.

Remove(HttpResponseHeader)
Remove(HttpResponseHeader)

Removes the specified header from the collection.

Remove(String)
Remove(String)

Removes the specified header from the collection.


Set(HttpRequestHeader, String)
Set(HttpRequestHeader, String)

Sets the specified header to the specified value.

Set(HttpResponseHeader, String)
Set(HttpResponseHeader, String)

Sets the specified header to the specified value.

Set(String, String)
Set(String, String)

Sets the specified header to the specified value.

ToByteArray()
ToByteArray()

Converts the WebHeaderCollection to a byte array.

ToString()
ToString()

This method is obsolete.

IEnumerable.GetEnumerator()
IEnumerable.GetEnumerator()

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Serializes this instance into the specified SerializationInfo object.


WebHeaderCollection.Add WebHeaderCollection.Add
I n this Article

Overloads
Add(String) Add(String)
Inserts the specified header into the collection.

Add(HttpRequestHeader, String) Add(HttpRequestHeader,


String) Inserts the specified header with the specified value into the
collection.

Add(HttpResponseHeader, String) Add(HttpResponseHeader,


String) Inserts the specified header with the specified value into the
collection.

Add(String, String) Add(String, String)


Inserts a header with the specified name and value into the
collection.

Add(String) Add(String)
Inserts the specified header into the collection.
public void Add (string header);
override this.Add : string -> unit

Parameters
header String String
The header to add, with the name and value separated by a colon.
Exceptions
ArgumentNullException ArgumentNullException
header is null or Empty.
ArgumentException ArgumentException
header does not contain a colon (:) character.

The length of value is greater than 65535.


-or-
The name part of header is Empty or contains invalid characters.
-or-
header is a restricted header that should be set with a property.
-or-
The value part of header contains invalid characters.
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length the string after the colon (:) is greater than 65535.
Examples
The following example adds a name/value pair to a WebHeaderCollection using the Add Method.
try {
//Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

//Get the headers associated with the request.


WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

Console.WriteLine("Configuring Webrequest to accept Danish and English language using 'Add'


method");

//Add the Accept-Language header (for Danish) in the request.


myWebHeaderCollection.Add("Accept-Language:da");

//Include English in the Accept-Langauge header.


myWebHeaderCollection.Add("Accept-Language","en;q=0.8");

//Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

//Print the headers for the request.


printHeaders(myWebHeaderCollection);
myHttpWebResponse.Close();
}
//Catch exception if trying to add a restricted header.
catch(ArgumentException e) {
Console.WriteLine(e.Message);
}
catch(WebException e) {
Console.WriteLine("
WebException is thrown.
Message is :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
}
}
catch(Exception e) {
Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}

Remarks
The header parameter must be specified in the format "name:value". If the specified header does not exist in the
collection, a new header is added to the collection.
If the header specified in header is already present in the collection, the value part of the header is concatenated with
the existing value.

Add(HttpRequestHeader, String) Add(HttpRequestHeader, String)


Inserts the specified header with the specified value into the collection.
public void Add (System.Net.HttpRequestHeader header, string value);
override this.Add : System.Net.HttpRequestHeader * string -> unit

Parameters
header HttpRequestHeader HttpRequestHeader
The header to add to the collection.
value String String
The content of the header.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpRequestHeader.
Remarks
If the specified header does not exist, the Add method inserts a new header into the list of header name/value pairs.
If the specified header is already present, value is added to the comma-separated list of values associated with the
header.

Add(HttpResponseHeader, String) Add(HttpResponseHeader,


String)
Inserts the specified header with the specified value into the collection.

public void Add (System.Net.HttpResponseHeader header, string value);


override this.Add : System.Net.HttpResponseHeader * string -> unit

Parameters
header HttpResponseHeader HttpResponseHeader
The header to add to the collection.
value String String
The content of the header.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.

InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpResponseHeader.
Remarks
If the specified header does not exist, the Add method inserts a new header into the list of header name/value pairs.
If the specified header is already present, value is added to the comma-separated list of values associated with the
header.

Add(String, String) Add(String, String)


Inserts a header with the specified name and value into the collection.

public override void Add (string name, string value);


override this.Add : string * string -> unit

Parameters
name String String
The header to add to the collection.
value String String
The content of the header.
Exceptions
ArgumentException ArgumentException
name is null , Empty, or contains invalid characters.
-or-
name is a restricted header that must be set with a property setting.
-or-
value contains invalid characters.

ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.
Examples
The following example adds a name/value pair to a WebHeaderCollection using the Add Method.
try {
//Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

//Get the headers associated with the request.


WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

Console.WriteLine("Configuring Webrequest to accept Danish and English language using 'Add'


method");

//Add the Accept-Language header (for Danish) in the request.


myWebHeaderCollection.Add("Accept-Language:da");

//Include English in the Accept-Langauge header.


myWebHeaderCollection.Add("Accept-Language","en;q=0.8");

//Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

//Print the headers for the request.


printHeaders(myWebHeaderCollection);
myHttpWebResponse.Close();
}
//Catch exception if trying to add a restricted header.
catch(ArgumentException e) {
Console.WriteLine(e.Message);
}
catch(WebException e) {
Console.WriteLine("
WebException is thrown.
Message is :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
}
}
catch(Exception e) {
Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}

Remarks
If the header specified in name does not exist, the Add method inserts a new header into the list of header name/value
pairs.
If the header specified in name is already present, value is added to the existing comma-separated list of values
associated with name .
WebHeaderCollection.AddWithoutValidate WebHeader
Collection.AddWithoutValidate
I n this Article
Inserts a header into the collection without checking whether the header is on the restricted header list.

protected void AddWithoutValidate (string headerName, string headerValue);


member this.AddWithoutValidate : string * string -> unit

Parameters
headerName String String
The header to add to the collection.
headerValue String String
The content of the header.
Exceptions
ArgumentException ArgumentException
headerName is null , Empty, or contains invalid characters.
-or-
headerValue contains invalid characters.
ArgumentOutOfRangeException ArgumentOutOfRangeException
headerName is not null and the length of headerValue is too long (greater than 65,535 characters).

Remarks
The AddWithoutValidate method adds a header to the collection without checking whether the header is on the
restricted header list.
WebHeaderCollection.AllKeys WebHeaderCollection.All
Keys
I n this Article
Gets all header names (keys) in the collection.

public override string[] AllKeys { get; }


member this.AllKeys : string[]

Returns
String[]
An array of type String containing all header names in a Web request.

Examples
The following code example uses the AllKeys property to get the header names a WebHeaderCollection.
if (args.Length == 0)
{
Console.WriteLine("must specify a URL!");
return;
}
string server = args[0];

// Create the web request


HttpWebRequest myHttpWebRequest =
(HttpWebRequest) WebRequest.Create(server);
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection =
myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++)


{
String header = myWebHeaderCollection.GetKey(i);
String[] values =
myWebHeaderCollection.GetValues(header);
if(values.Length > 0)
{
Console.WriteLine("The values of {0} header are : "
, header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated" +
"with the header");
}
Console.WriteLine("");

// Get the headers again, using new properties (Keys,


// AllKeys, Clear) and methods (Get and GetKey)

string[] headers = myWebHeaderCollection.AllKeys;


// enumerate through the header collection.
foreach (string s in headers)
{
Console.WriteLine("Header {0}, value {1}",
s,
myWebHeaderCollection.Get(s) );
}

Console.WriteLine("");

// show the use of Get(Int32) and GetValue(Int32)


if (myWebHeaderCollection.Count > 0)
{
// get the name and value of the first header
int index=0;
Console.WriteLine("Header {0}: name {1}, value {2}",
index,
myWebHeaderCollection.GetKey(index),
myWebHeaderCollection.Get(index));
}

myWebHeaderCollection.Clear();

myHttpWebResponse.Close();
WebHeaderCollection.Clear WebHeaderCollection.Clear
I n this Article
Removes all headers from the collection.
public override void Clear ();
override this.Clear : unit -> unit

Examples
The following code example clears the headers in a WebHeaderCollection.

if (args.Length == 0)
{
Console.WriteLine("must specify a URL!");
return;
}
string server = args[0];

// Create the web request


HttpWebRequest myHttpWebRequest =
(HttpWebRequest) WebRequest.Create(server);
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection =
myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++)


{
String header = myWebHeaderCollection.GetKey(i);
String[] values =
myWebHeaderCollection.GetValues(header);
if(values.Length > 0)
{
Console.WriteLine("The values of {0} header are : "
, header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated" +
"with the header");
}
Console.WriteLine("");

// Get the headers again, using new properties (Keys,


// AllKeys, Clear) and methods (Get and GetKey)

string[] headers = myWebHeaderCollection.AllKeys;

// enumerate through the header collection.


foreach (string s in headers)
{
Console.WriteLine("Header {0}, value {1}",
s,
myWebHeaderCollection.Get(s) );
}
Console.WriteLine("");

// show the use of Get(Int32) and GetValue(Int32)


if (myWebHeaderCollection.Count > 0)
{
// get the name and value of the first header
int index=0;
Console.WriteLine("Header {0}: name {1}, value {2}",
index,
myWebHeaderCollection.GetKey(index),
myWebHeaderCollection.Get(index));
}

myWebHeaderCollection.Clear();

myHttpWebResponse.Close();
WebHeaderCollection.Count WebHeaderCollection.
Count
I n this Article
Gets the number of headers in the collection.

public override int Count { get; }


member this.Count : int

Returns
Int32 Int32
An Int32 indicating the number of headers in a request.

Examples
The following code example uses the Count property to iterate through a WebHeaderCollection.
if (args.Length == 0)
{
Console.WriteLine("must specify a URL!");
return;
}
string server = args[0];

// Create the web request


HttpWebRequest myHttpWebRequest =
(HttpWebRequest) WebRequest.Create(server);
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection =
myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++)


{
String header = myWebHeaderCollection.GetKey(i);
String[] values =
myWebHeaderCollection.GetValues(header);
if(values.Length > 0)
{
Console.WriteLine("The values of {0} header are : "
, header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated" +
"with the header");
}
Console.WriteLine("");

// Get the headers again, using new properties (Keys,


// AllKeys, Clear) and methods (Get and GetKey)

string[] headers = myWebHeaderCollection.AllKeys;


// enumerate through the header collection.
foreach (string s in headers)
{
Console.WriteLine("Header {0}, value {1}",
s,
myWebHeaderCollection.Get(s) );
}

Console.WriteLine("");

// show the use of Get(Int32) and GetValue(Int32)


if (myWebHeaderCollection.Count > 0)
{
// get the name and value of the first header
int index=0;
Console.WriteLine("Header {0}: name {1}, value {2}",
index,
myWebHeaderCollection.GetKey(index),
myWebHeaderCollection.Get(index));
}

myWebHeaderCollection.Clear();

myHttpWebResponse.Close();
WebHeaderCollection.Get WebHeaderCollection.Get
I n this Article

Overloads
Get(Int32) Get(Int32)
Gets the value of a particular header in the collection, specified
by an index into the collection.

Get(String) Get(String)
Gets the value of a particular header in the collection, specified
by the name of the header.

Get(Int32) Get(Int32)
Gets the value of a particular header in the collection, specified by an index into the collection.
public override string Get (int index);
override this.Get : int -> string

Parameters
index Int32 Int32
The zero-based index of the key to get from the collection.
Returns
String String
A String containing the value of the specified header.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
index is negative.
-or-
index exceeds the size of the collection.
Examples
The following code example uses the Get method to retrieve a header value in a WebHeaderCollection.
if (args.Length == 0)
{
Console.WriteLine("must specify a URL!");
return;
}
string server = args[0];

// Create the web request


HttpWebRequest myHttpWebRequest =
(HttpWebRequest) WebRequest.Create(server);
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse();
(HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection =
myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++)


{
String header = myWebHeaderCollection.GetKey(i);
String[] values =
myWebHeaderCollection.GetValues(header);
if(values.Length > 0)
{
Console.WriteLine("The values of {0} header are : "
, header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated" +
"with the header");
}
Console.WriteLine("");

// Get the headers again, using new properties (Keys,


// AllKeys, Clear) and methods (Get and GetKey)

string[] headers = myWebHeaderCollection.AllKeys;

// enumerate through the header collection.


foreach (string s in headers)
{
Console.WriteLine("Header {0}, value {1}",
s,
myWebHeaderCollection.Get(s) );
}

Console.WriteLine("");

// show the use of Get(Int32) and GetValue(Int32)


if (myWebHeaderCollection.Count > 0)
{
// get the name and value of the first header
int index=0;
Console.WriteLine("Header {0}: name {1}, value {2}",
index,
myWebHeaderCollection.GetKey(index),
myWebHeaderCollection.Get(index));
}

myWebHeaderCollection.Clear();

myHttpWebResponse.Close();

Get(String) Get(String)
Gets the value of a particular header in the collection, specified by the name of the header.
public override string Get (string name);
override this.Get : string -> string

Parameters
name String String
The name of the Web header.
Returns
String String
A String holding the value of the specified header.
Examples
The following code example uses the Get property to retrieve header values in a WebHeaderCollection.

if (args.Length == 0)
{
Console.WriteLine("must specify a URL!");
return;
}
string server = args[0];

// Create the web request


HttpWebRequest myHttpWebRequest =
(HttpWebRequest) WebRequest.Create(server);
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection =
myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++)


{
String header = myWebHeaderCollection.GetKey(i);
String[] values =
myWebHeaderCollection.GetValues(header);
if(values.Length > 0)
{
Console.WriteLine("The values of {0} header are : "
, header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated" +
"with the header");
}
Console.WriteLine("");

// Get the headers again, using new properties (Keys,


// AllKeys, Clear) and methods (Get and GetKey)

string[] headers = myWebHeaderCollection.AllKeys;

// enumerate through the header collection.


foreach (string s in headers)
{
Console.WriteLine("Header {0}, value {1}",
s,
myWebHeaderCollection.Get(s) );
}

Console.WriteLine("");
// show the use of Get(Int32) and GetValue(Int32)
if (myWebHeaderCollection.Count > 0)
{
// get the name and value of the first header
int index=0;
Console.WriteLine("Header {0}: name {1}, value {2}",
index,
myWebHeaderCollection.GetKey(index),
myWebHeaderCollection.Get(index));
}

myWebHeaderCollection.Clear();

myHttpWebResponse.Close();

Remarks
This method returns null if there is no name header in the collection.
WebHeaderCollection.GetEnumerator WebHeader
Collection.GetEnumerator
I n this Article
Returns an enumerator that can iterate through the WebHeaderCollection instance.

public override System.Collections.IEnumerator GetEnumerator ();


override this.GetEnumerator : unit -> System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
An IEnumerator for the WebHeaderCollection.
WebHeaderCollection.GetKey WebHeaderCollection.Get
Key
I n this Article
Gets the header name at the specified position in the collection.

public override string GetKey (int index);


override this.GetKey : int -> string

Parameters
index Int32 Int32
The zero-based index of the key to get from the collection.
Returns
String String
A String holding the header name.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
index is negative.
-or-
index exceeds the size of the collection.

Examples
The following code example uses GetKey to get a header name in a WebHeaderCollection.
if (args.Length == 0)
{
Console.WriteLine("must specify a URL!");
return;
}
string server = args[0];

// Create the web request


HttpWebRequest myHttpWebRequest =
(HttpWebRequest) WebRequest.Create(server);
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse =
(HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection =
myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++)


{
String header = myWebHeaderCollection.GetKey(i);
String[] values =
myWebHeaderCollection.GetValues(header);
if(values.Length > 0)
{
Console.WriteLine("The values of {0} header are : "
Console.WriteLine("The values of {0} header are : "
, header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated" +
"with the header");
}
Console.WriteLine("");

// Get the headers again, using new properties (Keys,


// AllKeys, Clear) and methods (Get and GetKey)

string[] headers = myWebHeaderCollection.AllKeys;

// enumerate through the header collection.


foreach (string s in headers)
{
Console.WriteLine("Header {0}, value {1}",
s,
myWebHeaderCollection.Get(s) );
}

Console.WriteLine("");

// show the use of Get(Int32) and GetValue(Int32)


if (myWebHeaderCollection.Count > 0)
{
// get the name and value of the first header
int index=0;
Console.WriteLine("Header {0}: name {1}, value {2}",
index,
myWebHeaderCollection.GetKey(index),
myWebHeaderCollection.Get(index));
}

myWebHeaderCollection.Clear();

myHttpWebResponse.Close();
WebHeaderCollection.GetObjectData WebHeader
Collection.GetObjectData
I n this Article
Populates a SerializationInfo with the data needed to serialize the target object.

public override void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
WebHeaderCollection.GetValues WebHeaderCollection.
GetValues
I n this Article

Overloads
GetValues(String) GetValues(String)
Gets an array of header values stored in a header.

GetValues(Int32) GetValues(Int32)
Gets an array of header values stored in the index position
of the header collection.

GetValues(String) GetValues(String)
Gets an array of header values stored in a header.
public override string[] GetValues (string header);
override this.GetValues : string -> string[]

Parameters
header String String
The header to return.
Returns
String[]
An array of header strings.
Examples
The following example uses the GetValues method to retrieve an array of values for each header in the
WebHeaderCollection.
// Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");
myHttpWebRequest.Timeout = 1000;
// Get the associated response for the above request.
HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection = myHttpWebResponse.Headers;

for(int i = 0; i < myWebHeaderCollection.Count; i++) {


String header = myWebHeaderCollection.GetKey(i);
String[] values = myWebHeaderCollection.GetValues(header);
if(values.Length > 0) {
Console.WriteLine("The values of {0} header are : ", header);
for(int j = 0; j < values.Length; j++)
Console.WriteLine(" {0}", values[j]);
}
else
Console.WriteLine("There is no value associated with the header");
}
myHttpWebResponse.Close();

Remarks
GetValues returns the contents of the specified header as an array.

GetValues(Int32) GetValues(Int32)
Gets an array of header values stored in the index position of the header collection.

public override string[] GetValues (int index);


override this.GetValues : int -> string[]

Parameters
index Int32 Int32
The header index to return.
Returns
String[]
An array of header strings.
Remarks
GetValues returns the contents of the specified header as an array.
WebHeaderCollection.IEnumerable.GetEnumerator
I n this Article
System.Collections.IEnumerator IEnumerable.GetEnumerator ();

Returns
IEnumerator
WebHeaderCollection.ISerializable.GetObjectData
I n this Article
Serializes this instance into the specified SerializationInfo object.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The object into which this WebHeaderCollection will be serialized.
streamingContext StreamingContext
The destination of the serialization.
WebHeaderCollection.IsRestricted WebHeader
Collection.IsRestricted
I n this Article

Overloads
IsRestricted(String) IsRestricted(String)
Tests whether the specified HTTP header can be set for the
request.

IsRestricted(String, Boolean) IsRestricted(String, Boolean)


Tests whether the specified HTTP header can be set for the
request or the response.

IsRestricted(String) IsRestricted(String)
Tests whether the specified HTTP header can be set for the request.
public static bool IsRestricted (string headerName);
static member IsRestricted : string -> bool

Parameters
headerName String String
The header to test.
Returns
Boolean Boolean
true if the header is restricted; otherwise false .
Exceptions
ArgumentNullException ArgumentNullException
headerName is null or Empty.
ArgumentException ArgumentException
headerName contains invalid characters.
Examples
The following example checks the IsRestricted property to see if any headers are prohibited from being set.
try {
// Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

// Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection = myHttpWebResponse.Headers;

for (int i = 0; i < myWebHeaderCollection.Count;i++)


{
// Check if the first response header is restricted.
if(WebHeaderCollection.IsRestricted(myWebHeaderCollection.AllKeys[i]))
Console.WriteLine("'{0}' is a restricted header", myWebHeaderCollection.AllKeys[i]);
else
Console.WriteLine("'{0}' is not a restricted header", myWebHeaderCollection.AllKeys[i]);
}
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("
WebException is thrown.
Message is:" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
}
}
catch(Exception e) {
Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}

Remarks
The IsRestricted method returns true to indicate that a header is restricted and must be set using properties instead of
directly or is set by the system. The restricted headers are:
Accept
Connection
Content-Length
Content-Type
Date
Expect
Host
If-Modified-Since
Range
Referer
Transfer-Encoding
User-Agent
Proxy-Connection

IsRestricted(String, Boolean) IsRestricted(String, Boolean)


Tests whether the specified HTTP header can be set for the request or the response.

public static bool IsRestricted (string headerName, bool response);


static member IsRestricted : string * bool -> bool

Parameters
headerName String String
The header to test.
response Boolean Boolean
Does the Framework test the response or the request?
Returns
Boolean Boolean
true if the header is restricted; otherwise, false .

Exceptions
ArgumentNullException ArgumentNullException
headerName is null or Empty.
ArgumentException ArgumentException
headerName contains invalid characters.
Examples
The following example checks the IsRestricted property to see if any request headers are prohibited from being set.
try {
// Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

// Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

// Get the headers associated with the response.


WebHeaderCollection myWebHeaderCollection = myHttpWebResponse.Headers;

for (int i = 0; i < myWebHeaderCollection.Count;i++)


{
// Check if the first response header is restricted.
if(WebHeaderCollection.IsRestricted(myWebHeaderCollection.AllKeys[i]))
Console.WriteLine("'{0}' is a restricted header", myWebHeaderCollection.AllKeys[i]);
else
Console.WriteLine("'{0}' is not a restricted header", myWebHeaderCollection.AllKeys[i]);
}
myHttpWebResponse.Close();
}
catch(WebException e) {
Console.WriteLine("
WebException is thrown.
Message is:" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
}
}
catch(Exception e) {
Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}

Remarks
The IsRestricted method returns true to indicate that a request or response header is restricted and must be set using
properties instead of directly or is set by the system. The restricted headers are:
Accept
Connection
Content-Length
Content-Type
Date
Expect
Host
If-Modified-Since
Range
Referer
Transfer-Encoding
User-Agent
Proxy-Connection
WebHeaderCollection.Item[String] WebHeader
Collection.Item[String]
I n this Article

Overloads
Item[HttpRequestHeader] Item[HttpRequestHeader]
Gets or sets the specified request header.

Item[HttpResponseHeader] Item[HttpResponseHeader]
Gets or sets the specified response header.

Item[String] Item[String]

Item[HttpRequestHeader] Item[HttpRequestHeader]
Gets or sets the specified request header.
public string this[System.Net.HttpRequestHeader header] { get; set; }
member this.Item(System.Net.HttpRequestHeader) : string with get, set

Parameters
header HttpRequestHeader HttpRequestHeader
The request header value.
Returns
String String
A String instance containing the specified header value.
Exceptions
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpRequestHeader.

Item[HttpResponseHeader] Item[HttpResponseHeader]
Gets or sets the specified response header.
public string this[System.Net.HttpResponseHeader header] { get; set; }
member this.Item(System.Net.HttpResponseHeader) : string with get, set

Parameters
header HttpResponseHeader HttpResponseHeader
The response header value.
Returns
String String
A String instance containing the specified header.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpResponseHeader.

Item[String] Item[String]
public string this[string name] { get; set; }
member this.Item(string) : string with get, set

Parameters
name String String
Returns
String String
WebHeaderCollection.Keys WebHeaderCollection.Keys
I n this Article
Gets the collection of header names (keys) in the collection.
public override System.Collections.Specialized.NameObjectCollectionBase.KeysCollection Keys { get; }
member this.Keys : System.Collections.Specialized.NameObjectCollectionBase.KeysCollection

Returns
NameObjectCollectionBase.KeysCollection NameObjectCollectionBase.KeysCollection
A NameObjectCollectionBase.KeysCollection containing all header names in a Web request.
WebHeaderCollection.OnDeserialization WebHeader
Collection.OnDeserialization
I n this Article
Implements the ISerializable interface and raises the deserialization event when the deserialization is complete.

public override void OnDeserialization (object sender);


override this.OnDeserialization : obj -> unit

Parameters
sender Object Object
The source of the deserialization event.
WebHeaderCollection.Remove WebHeaderCollection.
Remove
I n this Article

Overloads
Remove(HttpRequestHeader) Remove(HttpRequestHeader)
Removes the specified header from the collection.

Remove(HttpResponseHeader) Remove(HttpResponseHeader)
Removes the specified header from the collection.

Remove(String) Remove(String)
Removes the specified header from the collection.

Remove(HttpRequestHeader) Remove(HttpRequestHeader)
Removes the specified header from the collection.
public void Remove (System.Net.HttpRequestHeader header);
override this.Remove : System.Net.HttpRequestHeader -> unit

Parameters
header HttpRequestHeader HttpRequestHeader
The HttpRequestHeader instance to remove from the collection.
Exceptions
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpRequestHeader.
Remarks
Remove deletes the specified header from the collection. If the specified header does not exist, the method does
nothing.

Remove(HttpResponseHeader) Remove(HttpResponseHeader)
Removes the specified header from the collection.
public void Remove (System.Net.HttpResponseHeader header);
override this.Remove : System.Net.HttpResponseHeader -> unit

Parameters
header HttpResponseHeader HttpResponseHeader
The HttpResponseHeader instance to remove from the collection.
Exceptions
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpResponseHeader.
Remarks
Remove deletes the specified header from the collection. If the specified header does not exist, the method does
nothing.

Remove(String) Remove(String)
Removes the specified header from the collection.
public override void Remove (string name);
override this.Remove : string -> unit

Parameters
name String String
The name of the header to remove from the collection.
Exceptions
ArgumentNullException ArgumentNullException
name is null Empty.

ArgumentException ArgumentException
name is a restricted header.
-or-
name contains invalid characters.
Examples
The following example uses the Remove method to remove a header from the WebHeaderCollection. After the header
is removed, this example prints all existing headers to the screen to prove that it has been removed.
try {
// Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

// Get the headers associated with the request.


WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

// Set the Cache-Control header.


myWebHeaderCollection.Set("Cache-Control", "no-cache");

// Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

// Print the headers of the request to console.


Console.WriteLine("Print request headers after adding Cache-Control for first request:");
printHeaders(myHttpWebRequest.Headers);

// Remove the Cache-Control header for the new request.


myWebHeaderCollection.Remove("Cache-Control");

// Get the response for the new request.


myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

// Print the headers of the new request without the Cache-Control header.
Console.WriteLine("Print request headers after removing Cache-Control for the new request:");
printHeaders(myHttpWebRequest.Headers);
myHttpWebResponse.Close();
}
// Catch exception if trying to remove a restricted header.
catch(ArgumentException e) {
Console.WriteLine("Error : Trying to remove a restricted header");
Console.WriteLine("ArgumentException is thrown. Message is :" + e.Message);
}
catch(WebException e) {
Console.WriteLine("WebException is thrown. Message is :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
}
}
catch(Exception e) {
Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}

Remarks
Remove deletes the specified header from the collection. If the specified header does not exist, the method returns.
WebHeaderCollection.Set WebHeaderCollection.Set
I n this Article

Overloads
Set(HttpRequestHeader, String) Set(HttpRequestHeader,
String) Sets the specified header to the specified value.

Set(HttpResponseHeader, String) Set(HttpResponseHeader,


String) Sets the specified header to the specified value.

Set(String, String) Set(String, String)


Sets the specified header to the specified value.

Set(HttpRequestHeader, String) Set(HttpRequestHeader, String)


Sets the specified header to the specified value.
public void Set (System.Net.HttpRequestHeader header, string value);
override this.Set : System.Net.HttpRequestHeader * string -> unit

Parameters
header HttpRequestHeader HttpRequestHeader
The HttpRequestHeader value to set.
value String String
The content of the header to set.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpRequestHeader.
Remarks
If the header specified in the header does not exist, the Set method inserts a new header into the list of header
name/value pairs.
If the header specified in header is already present, value replaces the existing value.

Set(HttpResponseHeader, String) Set(HttpResponseHeader, String)


Sets the specified header to the specified value.
public void Set (System.Net.HttpResponseHeader header, string value);
override this.Set : System.Net.HttpResponseHeader * string -> unit
Parameters
header HttpResponseHeader HttpResponseHeader
The HttpResponseHeader value to set.
value String String
The content of the header to set.
Exceptions
ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.
InvalidOperationException InvalidOperationException
This WebHeaderCollection instance does not allow instances of HttpResponseHeader.
Remarks
If the header specified in the header does not exist, the Set method inserts a new header into the list of header
name/value pairs.
If the header specified in header is already present, value replaces the existing value.

Set(String, String) Set(String, String)


Sets the specified header to the specified value.

public override void Set (string name, string value);


override this.Set : string * string -> unit

Parameters
name String String
The header to set.
value String String
The content of the header to set.
Exceptions
ArgumentNullException ArgumentNullException
name is null or Empty.

ArgumentOutOfRangeException ArgumentOutOfRangeException
The length of value is greater than 65535.

ArgumentException ArgumentException
name is a restricted header.
-or-
name or value contain invalid characters.
Examples
The following example uses the Set method to set the value of an existing header.

try {
// Create a web request for "www.msn.com".
HttpWebRequest myHttpWebRequest = (HttpWebRequest) WebRequest.Create("http://www.msn.com");

// Get the headers associated with the request.


WebHeaderCollection myWebHeaderCollection = myHttpWebRequest.Headers;

// Set the Cache-Control header in the request.


myWebHeaderCollection.Set("Cache-Control", "no-cache");

// Get the associated response for the above request.


HttpWebResponse myHttpWebResponse = (HttpWebResponse) myHttpWebRequest.GetResponse();

Console.WriteLine ("Headers after 'Set' method is used on Cache-Control :");


// Print the headers for the request.
PrintHeaders(myWebHeaderCollection);
myHttpWebResponse.Close();
}
// Catch exception if trying to set a restricted header.
catch(ArgumentException e) {
Console.WriteLine("ArgumentException is thrown. Message is :" + e.Message);
}
catch(WebException e) {
Console.WriteLine("WebException is thrown. Message is :" + e.Message);
if(e.Status == WebExceptionStatus.ProtocolError) {
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
Console.WriteLine("Server : {0}", ((HttpWebResponse)e.Response).Server);
}
}
catch(Exception e) {
Console.WriteLine("Exception is thrown. Message is :" + e.Message);
}

Remarks
If the header specified in the header does not exist, the Set method inserts a new header into the list of header
name/value pairs.
If the header specified in header is already present, value replaces the existing value.
WebHeaderCollection.ToByteArray WebHeader
Collection.ToByteArray
I n this Article
Converts the WebHeaderCollection to a byte array.

public byte[] ToByteArray ();


member this.ToByteArray : unit -> byte[]

Returns
Byte[]
A Byte array holding the header collection.
WebHeaderCollection.ToString WebHeaderCollection.To
String
I n this Article
This method is obsolete.

public override string ToString ();


override this.ToString : unit -> string

Returns
String String
The String representation of the collection.
WebHeaderCollection WebHeaderCollection
I n this Article

Overloads
WebHeaderCollection()
Initializes a new instance of the WebHeaderCollection class.

WebHeaderCollection(SerializationInfo, StreamingContext)
WebHeaderCollection(SerializationInfo, StreamingContext) Initializes a new instance of the WebHeaderCollection class
from the specified instances of the SerializationInfo and
StreamingContext classes.

WebHeaderCollection()
Initializes a new instance of the WebHeaderCollection class.
public WebHeaderCollection ();

WebHeaderCollection(SerializationInfo, StreamingContext)
WebHeaderCollection(SerializationInfo, StreamingContext)
Initializes a new instance of the WebHeaderCollection class from the specified instances of the SerializationInfo and
StreamingContext classes.
protected WebHeaderCollection (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.WebHeaderCollection : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.WebHeaderCollection

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo containing the information required to serialize the WebHeaderCollection.
streamingContext StreamingContext StreamingContext
A StreamingContext containing the source of the serialized stream associated with the new WebHeaderCollection.
Exceptions
ArgumentException ArgumentException
headerName contains invalid characters.
ArgumentNullException ArgumentNullException
headerName is a null reference or Empty.
Remarks
This constructor implements the ISerializable interface for the WebHeaderCollection class.
See XML and SOAP Serialization
Also
WebPermission WebPermission Class
Controls rights to access HTTP Internet resources.

D eclaration
[System.Serializable]
public sealed class WebPermission : System.Security.CodeAccessPermission,
System.Security.Permissions.IUnrestrictedPermission
type WebPermission = class
inherit CodeAccessPermission
interface IUnrestrictedPermission

I nheritance H ierarchy
Object Object
CodeAccessPermission CodeAccessPermission

Remarks
WebPermission provides a set of methods and properties to control access to Internet resources. You can use a
WebPermission to provide either restricted or unrestricted access to your resource, based on the PermissionState that
is set when the WebPermission is created.
Create a WebPermission instance by calling its constructor using one of the following sets of parameters:
No parameters. The default PermissionState is None.
A PermissionState. Specify either Unrestricted to allow any URI to be used in the target class, or None to allow access
only to URIs that you specify through the use of the AddPermission method.
A NetworkAccess value and a URI string. The specified URI has permissions granted by the NetworkAccess value.
A NetworkAccess specifier and URI regular expression.
The ConnectList and AcceptList hold the URIs to which you have granted access permission. To add a URI to either of
these lists, use AddPermission. If you pass Accept as the NetworkAccess parameter, the URI will be added to the
AcceptList. WebPermission will allow connections to your target class with URIs matching the AcceptList.
Cautio n

To deny access to an Internet resource, you must deny access to all the possible paths to that resource. This requires
calling WebPermission.WebPermission with state parameter set to Deny. A better approach is to allow access to the
specific resource only. For more information about this subject, refer to the NIB: Using the Deny Method topic.
Note

You need to deny access using only the resource canonical path. There is no need to use all the path's syntactical
variations.
Note

User name and default port information is stripped from the Uri before the comparison with the regular expression
argument that is supplied to the WebPermission(NetworkAccess, Regex) constructor. If the regular expression contains
user information or the default port number, then all incoming Uris will fail to match the regular expression.

Constructors
WebPermission()
WebPermission()

Creates a new instance of the WebPermission class.

WebPermission(PermissionState)
WebPermission(PermissionState)

Creates a new instance of the WebPermission class that passes all demands or fails all demands.

WebPermission(NetworkAccess, String)
WebPermission(NetworkAccess, String)

Initializes a new instance of the WebPermission class with the specified access rights for the specified URI.

WebPermission(NetworkAccess, Regex)
WebPermission(NetworkAccess, Regex)

Initializes a new instance of the WebPermission class with the specified access rights for the specified URI regular
expression.

Properties
AcceptList
AcceptList

This property returns an enumeration of a single accept permissions held by this WebPermission. The possible
objects types contained in the returned enumeration are String and Regex.

ConnectList
ConnectList

This property returns an enumeration of a single connect permissions held by this WebPermission. The possible
objects types contained in the returned enumeration are String and Regex.

Methods
AddPermission(NetworkAccess, String)
AddPermission(NetworkAccess, String)

Adds the specified URI string with the specified access rights to the current WebPermission.

AddPermission(NetworkAccess, Regex)
AddPermission(NetworkAccess, Regex)

Adds the specified URI with the specified access rights to the current WebPermission.
Copy()
Copy()

Creates a copy of a WebPermission.

FromXml(SecurityElement)
FromXml(SecurityElement)

Reconstructs a WebPermission from an XML encoding.

Intersect(IPermission)
Intersect(IPermission)

Returns the logical intersection of two WebPermission instances.

IsSubsetOf(IPermission)
IsSubsetOf(IPermission)

Determines whether the current WebPermission is a subset of the specified object.

IsUnrestricted()
IsUnrestricted()

Checks the overall permission state of the WebPermission.

ToXml()
ToXml()

Creates an XML encoding of a WebPermission and its current state.

Union(IPermission)
Union(IPermission)

Returns the logical union between two instances of the WebPermission class.

See Also
CodeAccessPermission CodeAccessPermission
PermissionState PermissionState
NetworkAccess NetworkAccess
WebPermission.AcceptList WebPermission.AcceptList
I n this Article
This property returns an enumeration of a single accept permissions held by this WebPermission. The possible objects
types contained in the returned enumeration are String and Regex.

public System.Collections.IEnumerator AcceptList { get; }


member this.AcceptList : System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
The IEnumerator interface that contains accept permissions.

Examples
The following example prints the URLs in the AcceptList to the console.

// Get all URI's with Accept permission.


IEnumerator myEnum1 = myWebPermission1.AcceptList;
Console.WriteLine("

The URIs with Accept permission are :


");
while (myEnum1.MoveNext())
{ Console.WriteLine(" The URI is : "+myEnum1.Current); }

Remarks
This property gets a list of local resources permitted by this WebPermission. The class to which you have applied
WebPermission only has permission to receive an incoming connection to local resources found in this list.
Note

You can add URIs to this list using AddPermission.


Note

A candidate URI string is checked against the list of relevant regular expressions (AcceptList or ConnectList) in two
ways. First, the candidate URI string is checked against the appropriate list; then, if there is no match, the candidate URI
string is converted into a Uri and checked against the appropriate list.
See AddPermission(NetworkAccess, String)AddPermission(NetworkAccess, String)
Also
WebPermission.AddPermission WebPermission.Add
Permission
I n this Article

Overloads
AddPermission(NetworkAccess, String) AddPermission(
NetworkAccess, String) Adds the specified URI string with the specified access rights
to the current WebPermission.

AddPermission(NetworkAccess, Regex) AddPermission(


NetworkAccess, Regex) Adds the specified URI with the specified access rights to the
current WebPermission.

AddPermission(NetworkAccess, String)
AddPermission(NetworkAccess, String)
Adds the specified URI string with the specified access rights to the current WebPermission.

public void AddPermission (System.Net.NetworkAccess access, string uriString);


member this.AddPermission : System.Net.NetworkAccess * string -> unit

Parameters
access NetworkAccess NetworkAccess
A NetworkAccess that specifies the access rights that are granted to the URI.
uriString String String
A string that describes the URI to which access rights are granted.
Exceptions
ArgumentNullException ArgumentNullException
uriString is null .
Examples
The following example demonstrates how to add access rights to particular URL strings.

// Allow access to the first set of resources.


myWebPermission1.AddPermission(NetworkAccess.Connect,"http://www.contoso.com/default.htm");
myWebPermission1.AddPermission(NetworkAccess.Connect,"http://www.adventure-works.com/default.htm");

// Check whether if the callers higher in the call stack have been granted
// access permissions.
myWebPermission1.Demand();

Remarks
If you have specified None as the PermissionState, use AddPermission to permit the use of uriString in the target
class. The way that uriString can be used by the target class is specified by access . Specify Accept as the access
parameter to add the URI specified by the uriString parameter to the list of URI accept strings, or specify Connect as
the access parameter to add the URI to the list of URI connect strings.
Note

Calling AddPermission on UnrestrictedWebPermission will have no effect, because permission is granted to all URIs.
Note

A candidate URI string is checked against the list of relevant regular expressions (AcceptList or ConnectList) in two
ways. First, the candidate URI string is checked against the appropriate list; then, if there is no match, the candidate URI
string is converted into a Uri and checked against the appropriate list.
See NetworkAccessNetworkAccess
Also

AddPermission(NetworkAccess, Regex)
AddPermission(NetworkAccess, Regex)
Adds the specified URI with the specified access rights to the current WebPermission.

public void AddPermission (System.Net.NetworkAccess access, System.Text.RegularExpressions.Regex


uriRegex);
member this.AddPermission : System.Net.NetworkAccess * System.Text.RegularExpressions.Regex -> unit

Parameters
access NetworkAccess NetworkAccess
A NetworkAccess that specifies the access rights that are granted to the URI.
uriRegex Regex Regex
A regular expression that describes the set of URIs to which access rights are granted.
Exceptions
ArgumentNullException ArgumentNullException
The uriRegex parameter is null .
Examples
The following example uses AddPermission to give access rights for the specified URI.

// Create a WebPermission.
WebPermission myWebPermission1 = new WebPermission();

// Allow Connect access to the specified URLs.


myWebPermission1.AddPermission(NetworkAccess.Connect,new Regex("http://www\\.contoso\\.com/.*",
RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline));

myWebPermission1.Demand();

Remarks
If you have specified None as the PermissionState, use AddPermission to allow the use of uriRegex in the target class.
Specify Accept as the access parameter to add the URI specified by the uriRegex parameter to the list of URI accept
strings, or specify Connect as the access parameter to add the URI to the list of URI connect strings.
Note

Calling AddPermission on an UnrestrictedWebPermission instance will have no effect as permission is granted to all
URIs.
Note

It is recommended that you create uriRegex using the RegexOptions.IgnoreCase, RegexOptions.Compiled, and
RegexOptions.Singleline flags.
Note

A candidate URI string is checked against the list of relevant regular expressions (AcceptList or ConnectList) in two
ways. First, the candidate URI string is checked against the appropriate list; then, if there is no match, the candidate URI
string is converted into a Uri and checked against the appropriate list.
See NetworkAccessNetworkAccess
Also
WebPermission.ConnectList WebPermission.ConnectList
I n this Article
This property returns an enumeration of a single connect permissions held by this WebPermission. The possible
objects types contained in the returned enumeration are String and Regex.

public System.Collections.IEnumerator ConnectList { get; }


member this.ConnectList : System.Collections.IEnumerator

Returns
IEnumerator IEnumerator
The IEnumerator interface that contains connect permissions.

Examples
The following example prints the URLs in the ConnectList to the console.

// Gets all URIs with Connect permission.


IEnumerator myEnum = myWebPermission1.ConnectList;
Console.WriteLine("
The URIs with Connect permission are :
");
while (myEnum.MoveNext())
{ Console.WriteLine(" The URI is : "+myEnum.Current); }

Remarks
This property gets a list of remote resources that are permitted by this WebPermission. The class to which you have
applied WebPermission only has permission to connect with resources found in this list.
Note

You can add URIs to this list using AddPermission.


Note

A candidate URI string is checked against the list of relevant regular expressions (AcceptList or ConnectList) in two
ways. First, the candidate URI string is checked against the appropriate list; then, if there is no match, the candidate URI
string is converted into a Uri and checked against the appropriate list.
See AddPermission(NetworkAccess, String)AddPermission(NetworkAccess, String)
Also
WebPermission.Copy WebPermission.Copy
I n this Article
Creates a copy of a WebPermission.
public override System.Security.IPermission Copy ();
override this.Copy : unit -> System.Security.IPermission

Returns
IPermission IPermission
A new instance of the WebPermission class that has the same values as the original.

Examples
The following example demonstrates how to create a second instance of WebPermission using Copy. This second
instance is identical to the first.
// Create another WebPermission instance that is the copy of the above WebPermission instance.
WebPermission myWebPermission2 = (WebPermission) myWebPermission1.Copy();

// Check whether all callers higher in the call stack have been granted the permissionor not.
myWebPermission2.Demand();

Remarks
The IPermission returned by this method represents the same access to resources as the original WebPermission. This
method overrides Copy and is implemented to support the IPermission interface.
WebPermission.FromXml WebPermission.FromXml
I n this Article
Reconstructs a WebPermission from an XML encoding.
public override void FromXml (System.Security.SecurityElement securityElement);
override this.FromXml : System.Security.SecurityElement -> unit

Parameters
securityElement SecurityElement SecurityElement
The XML encoding from which to reconstruct the WebPermission.
Exceptions
ArgumentNullException ArgumentNullException
The securityElement parameter is null.
ArgumentException ArgumentException
securityElement is not a permission element for this type.

Examples
The following example creates a System.Security.SecurityElement, populates its attributes, and uses FromXml to
transfer this information to an instance of WebPermission.

// Create a WebPermission without permission on the protected resource.


WebPermission myWebPermission1 = new WebPermission(PermissionState.None);

// Create a SecurityElement by calling the ToXml method on the WebPermission


// instance and display its attributes (which hold the XML encoding of
// the WebPermission).
Console.WriteLine("Attributes and Values of the WebPermission are :");
myWebPermission1.ToXml().ToString();

// Create another WebPermission with no permission on the protected resource.


WebPermission myWebPermission2 = new WebPermission(PermissionState.None);

//Converts the new WebPermission from XML using myWebPermission1.


myWebPermission2.FromXml(myWebPermission1.ToXml());

Remarks
The FromXml method reconstructs a WebPermission from an XML encoding that is defined by the SecurityElement
class.
Use the ToXml method to XML -encode the WebPermission, including state information.
See ToXml()ToXml()
Also
WebPermission.Intersect WebPermission.Intersect
I n this Article
Returns the logical intersection of two WebPermission instances.
public override System.Security.IPermission Intersect (System.Security.IPermission target);
override this.Intersect : System.Security.IPermission -> System.Security.IPermission

Parameters
target IPermission IPermission
The WebPermission to compare with the current instance.
Returns
IPermission IPermission
A new WebPermission that represents the intersection of the current instance and the target parameter. If the
intersection is empty, the method returns null .
Exceptions
ArgumentException ArgumentException
target is not null or of type WebPermission

Examples
The following example shows how to create an instance of WebPermission using the logical intersection of two existing
WebPermission instances.

// Create a third WebPermission instance via the logical intersection of the previous
// two WebPermission instances.
WebPermission myWebPermission3 =(WebPermission) myWebPermission1.Intersect(myWebPermission2);

Console.WriteLine("
Attributes and Values of the WebPermission instance after the Intersect are:
");
Console.WriteLine(myWebPermission3.ToXml().ToString());

Remarks
Intersect returns a WebPermission that contains those permissions that are common in both target and the current
instance.
This method overrides Intersect and is implemented to support the IPermission interface.
WebPermission.IsSubsetOf WebPermission.IsSubsetOf
I n this Article
Determines whether the current WebPermission is a subset of the specified object.
public override bool IsSubsetOf (System.Security.IPermission target);
override this.IsSubsetOf : System.Security.IPermission -> bool

Parameters
target IPermission IPermission
The WebPermission to compare to the current WebPermission.
Returns
Boolean Boolean
true if the current instance is a subset of the target parameter; otherwise, false . If the target is null , the method
returns true for an empty current permission that is not unrestricted and false otherwise.
Exceptions
ArgumentException ArgumentException
The target parameter is not an instance of WebPermission.
NotSupportedException NotSupportedException
The current instance contains a Regex-encoded right and there is not exactly the same right found in the target
instance.

Examples
The following example uses IsSubsetOf to determine whether the access rights found in one instance of
WebPermission are found in another instance of WebPermission.

// Create the target permission.


WebPermission targetPermission = new WebPermission();
targetPermission.AddPermission(NetworkAccess.Connect, new Regex("www\\.contoso\\.com/Public/.*"));

// Create the permission for a URI matching target.


WebPermission connectPermission = new WebPermission();
connectPermission.AddPermission(NetworkAccess.Connect, "www.contoso.com/Public/default.htm");

//The following statement prints true.


Console.WriteLine("Is the second URI a subset of the first one?: " +
connectPermission.IsSubsetOf(targetPermission));

Remarks
If the current WebPermission specifies a set of associated resources that is wholly contained by the target parameter,
then the current WebPermission is a subset of target . This method overrides IsSubsetOf and is implemented to
support the IPermission interface.
WebPermission.IsUnrestricted WebPermission.Is
Unrestricted
I n this Article
Checks the overall permission state of the WebPermission.

public bool IsUnrestricted ();


override this.IsUnrestricted : unit -> bool

Returns
Boolean Boolean
true if the WebPermission was created with the UnrestrictedPermissionState; otherwise, false .

Remarks
If WebPermission is Unrestricted, then the target class can use all URIs. Otherwise, specific permission must be given
for any URI you want to use with the target class.
Note

Use AddPermission to add a URI and specify its permissions.


See AddPermission(NetworkAccess, String)AddPermission(NetworkAccess, String)
Also
WebPermission.ToXml WebPermission.ToXml
I n this Article
Creates an XML encoding of a WebPermission and its current state.
public override System.Security.SecurityElement ToXml ();
override this.ToXml : unit -> System.Security.SecurityElement

Returns
SecurityElement SecurityElement
A SecurityElement that contains an XML -encoded representation of the WebPermission, including state information.

Examples
The following example demonstrates how to use ToXml to create a System.Security.SecurityElement and print its
attributes to the console.

// Create a WebPermission without permission on the protected resource.


WebPermission myWebPermission1 = new WebPermission(PermissionState.None);

// Create a SecurityElement by calling the ToXml method on the WebPermission


// instance and display its attributes (which hold the XML encoding of
// the WebPermission).
Console.WriteLine("Attributes and Values of the WebPermission are :");
myWebPermission1.ToXml().ToString();

// Create another WebPermission with no permission on the protected resource.


WebPermission myWebPermission2 = new WebPermission(PermissionState.None);

//Converts the new WebPermission from XML using myWebPermission1.


myWebPermission2.FromXml(myWebPermission1.ToXml());

Remarks
Use the FromXml method to restore the state information from a SecurityElement.
See FromXml(SecurityElement)FromXml(SecurityElement)
Also
WebPermission.Union WebPermission.Union
I n this Article
Returns the logical union between two instances of the WebPermission class.
public override System.Security.IPermission Union (System.Security.IPermission target);
override this.Union : System.Security.IPermission -> System.Security.IPermission

Parameters
target IPermission IPermission
The WebPermission to combine with the current WebPermission.
Returns
IPermission IPermission
A WebPermission that represents the union of the current instance and the target parameter. If either WebPermission
is Unrestricted, the method returns a WebPermission that is Unrestricted. If the target is null , the method returns a
copy of the current WebPermission.
Exceptions
ArgumentException ArgumentException
target is not null or of type WebPermission.

Examples
The following example takes the logical union of two WebPermission instances to create a third instance of
WebPermission.

// Create another WebPermission that is the Union of previous two WebPermission


// instances.
WebPermission myWebPermission3 =(WebPermission) myWebPermission1.Union(myWebPermission2);
Console.WriteLine("
Attributes and values of the WebPermission after the Union are : ");
// Display the attributes,values and children.
Console.WriteLine(myWebPermission3.ToXml().ToString());

Remarks
Union returns a WebPermission that contains all the permissions in both target and the current instance.
See PermissionStatePermissionState
Also
WebPermission WebPermission
I n this Article

Overloads
WebPermission()
Creates a new instance of the WebPermission class.

WebPermission(PermissionState) WebPermission(Permission
State) Creates a new instance of the WebPermission class that passes
all demands or fails all demands.

WebPermission(NetworkAccess, String) WebPermission(


NetworkAccess, String) Initializes a new instance of the WebPermission class with the
specified access rights for the specified URI.

WebPermission(NetworkAccess, Regex) WebPermission(


NetworkAccess, Regex) Initializes a new instance of the WebPermission class with the
specified access rights for the specified URI regular expression.

WebPermission()
Creates a new instance of the WebPermission class.
public WebPermission ();

Remarks
Creates a new instance of the WebPermission class. This constructor creates an empty permission that does not grant
any rights.
See IsUnrestricted()IsUnrestricted()
Also

WebPermission(PermissionState) WebPermission(PermissionState)
Creates a new instance of the WebPermission class that passes all demands or fails all demands.
public WebPermission (System.Security.Permissions.PermissionState state);
new System.Net.WebPermission : System.Security.Permissions.PermissionState ->
System.Net.WebPermission

Parameters
state PermissionState PermissionState
A PermissionState value.
Examples
The following example creates an instance of WebPermission and gives access rights to specific URLs.
// Create a WebPermission instance.
WebPermission myWebPermission1 = new WebPermission(PermissionState.None);

// Allow access to the first set of URL's.


myWebPermission1.AddPermission(NetworkAccess.Connect,"http://www.microsoft.com/default.htm");
myWebPermission1.AddPermission(NetworkAccess.Connect,"http://www.msn.com");

// Check whether all callers higher in the call stack have been granted the permissionor not.
myWebPermission1.Demand();

Remarks
The value of the state parameter is either PermissionState.None or PermissionState.Unrestricted, respectively
yielding fully restricted or fully unrestricted access to all security variables. If you specify PermissionState.None, then
you can give access to individual URIs using AddPermission.

WebPermission(NetworkAccess, String)
WebPermission(NetworkAccess, String)
Initializes a new instance of the WebPermission class with the specified access rights for the specified URI.

public WebPermission (System.Net.NetworkAccess access, string uriString);


new System.Net.WebPermission : System.Net.NetworkAccess * string -> System.Net.WebPermission

Parameters
access NetworkAccess NetworkAccess
A NetworkAccess value that indicates what kind of access to grant to the specified URI. Accept indicates that the
application is allowed to accept connections from the Internet on a local resource. Connect indicates that the
application is allowed to connect to specific Internet resources.
uriString String String
A URI string to which access rights are granted.
Exceptions
ArgumentNullException ArgumentNullException
uriString is null .
Examples
The following example creates a new instance of WebPermission with connect rights for the specified URI.

// Create a WebPermission.instance.
WebPermission myWebPermission1 = new
WebPermission(NetworkAccess.Connect,"http://www.contoso.com/default.htm");
myWebPermission1.Demand();

Remarks
This constructor initializes a WebPermission and grants its target permission to either make a remote host connection
or accept a remote host connection using the URI described by the uriString parameter.
See RegexRegex
Also
WebPermission(NetworkAccess, Regex)
WebPermission(NetworkAccess, Regex)
Initializes a new instance of the WebPermission class with the specified access rights for the specified URI regular
expression.

public WebPermission (System.Net.NetworkAccess access, System.Text.RegularExpressions.Regex


uriRegex);
new System.Net.WebPermission : System.Net.NetworkAccess * System.Text.RegularExpressions.Regex ->
System.Net.WebPermission

Parameters
access NetworkAccess NetworkAccess
A NetworkAccess value that indicates what kind of access to grant to the specified URI. Accept indicates that the
application is allowed to accept connections from the Internet on a local resource. Connect indicates that the
application is allowed to connect to specific Internet resources.
uriRegex Regex Regex
A regular expression that describes the URI to which access is to be granted.
Examples
The following example creates a new instance of WebPermission with connect rights for the specified
System.Text.RegularExpressions.Regex.

// Create an instance of 'Regex' that accepts all URL's containing the host
// fragment 'www.contoso.com'.
Regex myRegex = new Regex(@"http://www\.contoso\.com/.*");

// Create a WebPermission that gives the permissions to all the hosts containing
// the same fragment.
WebPermission myWebPermission = new WebPermission(NetworkAccess.Connect,myRegex);

// Checks all callers higher in the call stack have been granted the permission.
myWebPermission.Demand();

Remarks
This constructor initializes a WebPermission and grants its target permission to either make a remote host connection
or accept a remote host connection using the URI described by the uriRegex parameter.
Note

It is recommended that you create uriRegex using the RegexOptions.IgnoreCase, RegexOptions.Compiled, and
RegexOptions.Singleline flags.
Note

A candidate URI string is checked against the list of relevant regular expressions (AcceptList or ConnectList) in two
ways. First, the candidate URI string is checked against the appropriate list; then, if there is no match, the candidate URI
string is converted into a Uri and checked against the appropriate list.
See RegexRegex
Also
WebPermissionAttribute WebPermissionAttribute Class
Specifies permission to access Internet resources. This class cannot be inherited.

D eclaration
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Constructor | System.AttributeTargets.Method |
System.AttributeTargets.Struct, AllowMultiple=true, Inherited=false)]
[System.AttributeUsage(System.AttributeTargets.Assembly | System.AttributeTargets.Class |
System.AttributeTargets.Struct | System.AttributeTargets.Constructor |
System.AttributeTargets.Method, AllowMultiple=true, Inherited=false)]
[System.Serializable]
public sealed class WebPermissionAttribute :
System.Security.Permissions.CodeAccessSecurityAttribute
type WebPermissionAttribute = class
inherit CodeAccessSecurityAttribute

I nheritance H ierarchy
Object Object
Attribute Attribute
SecurityAttribute SecurityAttribute
CodeAccessSecurityAttribute CodeAccessSecurityAttribute

Remarks
WebPermissionAttribute allows you to declaratively specify which URI strings and regular expression strings your class
can use.
The security information specified in the WebPermissionAttribute is stored in the metadata of the attribute target,
which is the class to which WebPermissionAttribute is applied. The system accesses this information at run time. The
System.Security.Permissions.SecurityAction passed to the constructor determines the allowable
WebPermissionAttribute targets. The system uses the WebPermission returned by the CreatePermission method to
convert the security information of the attribute target to a serializable form stored in metadata.
Note

WebPermissionAttribute is used only for Declarative Security. For Imperative Security, use the corresponding
WebPermission.

Constructors
WebPermissionAttribute(SecurityAction)
WebPermissionAttribute(SecurityAction)

Initializes a new instance of the WebPermissionAttribute class with a value that specifies the security actions that
can be performed on this class.

Properties
Accept
Accept

Gets or sets the URI string accepted by the current WebPermissionAttribute.


AcceptPattern
AcceptPattern

Gets or sets a regular expression pattern that describes the URI accepted by the current WebPermissionAttribute.

Connect
Connect

Gets or sets the URI connection string controlled by the current WebPermissionAttribute.

ConnectPattern
ConnectPattern

Gets or sets a regular expression pattern that describes the URI connection controlled by the current
WebPermissionAttribute.

Methods
CreatePermission()
CreatePermission()

Creates and returns a new instance of the WebPermission class.


WebPermissionAttribute.Accept WebPermissionAttribute.
Accept
I n this Article
Gets or sets the URI string accepted by the current WebPermissionAttribute.

public string Accept { get; set; }


member this.Accept : string with get, set

Returns
String String
A string containing the URI accepted by the current WebPermissionAttribute.
Exceptions
ArgumentException ArgumentException
Accept is not null when you attempt to set the value. If you wish to specify more than one Accept URI, use an
additional attribute declaration statement.

Examples
The following example demonstrates how to use WebPermissionAttribute to specify an allowable Accept string.

// Deny access to a specific resource by setting the Accept property.


[WebPermission(SecurityAction.Deny, Accept=@"http://www.contoso.com/Private.htm")]

public static void CheckAcceptPermission(string uriToCheck)


{
WebPermission permissionToCheck = new WebPermission();
permissionToCheck.AddPermission(NetworkAccess.Accept, uriToCheck);
permissionToCheck.Demand();
}

public static void demoDenySite()


{
//Pass the security check when accessing allowed resources.
CheckAcceptPermission("http://www.contoso.com/");
Console.WriteLine("Public page has passed Accept permission check");

try
{
//Throw a SecurityException when trying to access not allowed resources.
CheckAcceptPermission("http://www.contoso.com/Private.htm");
Console.WriteLine("This line will not be printed");
}
catch (SecurityException e)
{
Console.WriteLine("Exception trying to access private resource:" + e.Message);
}

Remarks
When applying WebPermissionAttribute to your class, this property specifies what URI string will be accepted for use
within your class. This permission is applied when the security system calls CreatePermission. This property is write-
once.
See Introducing Pluggable Protocols
Also
WebPermissionAttribute.AcceptPattern WebPermission
Attribute.AcceptPattern
I n this Article
Gets or sets a regular expression pattern that describes the URI accepted by the current WebPermissionAttribute.

public string AcceptPattern { get; set; }


member this.AcceptPattern : string with get, set

Returns
String String
A string containing a regular expression pattern that describes the URI accepted by the current
WebPermissionAttribute. This string must be escaped according to the rules for encoding a Regex constructor string.
Exceptions
ArgumentException ArgumentException
AcceptPattern is not null when you attempt to set the value. If you wish to specify more than one Accept URI, use an
additional attribute declaration statement.

Examples
The following example demonstrates how to use WebPermissionAttribute to specify an allowable AcceptPattern.
[WebPermission(SecurityAction.Deny, AcceptPattern=@"http://www\.contoso\.com/Private/.*")]

public static void CheckAcceptPermission(string uriToCheck) {

WebPermission permissionToCheck = new WebPermission();


permissionToCheck.AddPermission(NetworkAccess.Accept, uriToCheck);
permissionToCheck.Demand();
}

public static void demoDenySite() {


//Passes a security check.
CheckAcceptPermission("http://www.contoso.com/Public/page.htm");
Console.WriteLine("Public page has passed Accept permission check");

try {
//Throws a SecurityException.
CheckAcceptPermission("http://www.contoso.com/Private/page.htm");
Console.WriteLine("This line will not be printed");
}
catch (SecurityException e) {
Console.WriteLine("Expected exception: " + e.Message);
}

Remarks
When applying WebPermissionAttribute to your class, this property specifies what regular expression string will be
accepted for use within your class. This property is write-once.
See Regular Expression Language - Quick Reference
Also
WebPermissionAttribute.Connect WebPermission
Attribute.Connect
I n this Article
Gets or sets the URI connection string controlled by the current WebPermissionAttribute.

public string Connect { get; set; }


member this.Connect : string with get, set

Returns
String String
A string containing the URI connection controlled by the current WebPermissionAttribute.
Exceptions
ArgumentException ArgumentException
Connect is not null when you attempt to set the value. If you wish to specify more than one Connect URI, use an
additional attribute declaration statement.

Examples
The following example demonstrates how to use WebPermissionAttribute to specify an allowable Connect string.

// Set the WebPermissionAttribute Connect property.


[WebPermission(SecurityAction.Deny, Connect=@"http://www.contoso.com/Private.htm")]

public static void demoDenySite()


{
//Pass the security check.
CheckConnectPermission("http://www.contoso.com/Public.htm");
Console.WriteLine("Public page has passed connect permission check");

try
{
//Throw a SecurityException.
CheckConnectPermission("http://www.contoso.com/Private.htm");
Console.WriteLine("This line will not be printed");
}
catch (SecurityException e) {
Console.WriteLine("Expected exception" + e.Message);
}

public static void CheckConnectPermission(string uriToCheck) {


WebPermission permissionToCheck = new WebPermission();
permissionToCheck.AddPermission(NetworkAccess.Connect, uriToCheck);
permissionToCheck.Demand();
}

Remarks
When applying WebPermissionAttribute to your class, this property specifies what URI connection is accepted for use
within your class. This property is write-once.
See Introducing Pluggable Protocols
Also
WebPermissionAttribute.ConnectPattern WebPermission
Attribute.ConnectPattern
I n this Article
Gets or sets a regular expression pattern that describes the URI connection controlled by the current
WebPermissionAttribute.
public string ConnectPattern { get; set; }
member this.ConnectPattern : string with get, set

Returns
String String
A string containing a regular expression pattern that describes the URI connection controlled by this
WebPermissionAttribute.
Exceptions
ArgumentException ArgumentException
ConnectPattern is not null when you attempt to set the value. If you wish to specify more than one connect URI, use
an additional attribute declaration statement.

Examples
The following example demonstrates how to use WebPermissionAttribute to specify an allowable ConnectPattern.

// Set the WebPermissionAttribute ConnectPattern property.


[WebPermission(SecurityAction.Deny, ConnectPattern=@"http://www\.contoso\.com/Private/.*")]

public static void CheckConnectPermission(string uriToCheck)


{
WebPermission permissionToCheck = new WebPermission();
permissionToCheck.AddPermission(NetworkAccess.Connect, uriToCheck);
permissionToCheck.Demand();
}

public static void demoDenySite() {


//Pass the security check.
CheckConnectPermission("http://www.contoso.com/Public/page.htm");
Console.WriteLine("Public page has passed Connect permission check");

try
{
//Throw a SecurityException.
CheckConnectPermission("http://www.contoso.com/Private/page.htm");
Console.WriteLine("This line will not be printed");
}
catch (SecurityException e)
{
Console.WriteLine("Expected exception" + e.Message);
}

Remarks
When applying WebPermissionAttribute to your class, this property specifies what regular expression connect string is
accepted for use within your class. This property is write-once.
See Regular Expression Language - Quick Reference
Also
WebPermissionAttribute.CreatePermission Web
PermissionAttribute.CreatePermission
I n this Article
Creates and returns a new instance of the WebPermission class.

public override System.Security.IPermission CreatePermission ();


override this.CreatePermission : unit -> System.Security.IPermission

Returns
IPermission IPermission
A WebPermission corresponding to the security declaration.

Remarks
The CreatePermission method is called by the security system, not by application code.
The security information described by WebPermissionAttribute is stored in the metadata of the attribute target, which
is the class to which WebPermissionAttribute is applied. The system accesses the information at run time. The system
uses the WebPermission returned by CreatePermission to convert the security information of the attribute target to a
serializable form stored in metadata.
WebPermissionAttribute WebPermissionAttribute
I n this Article
Initializes a new instance of the WebPermissionAttribute class with a value that specifies the security actions that can
be performed on this class.

public WebPermissionAttribute (System.Security.Permissions.SecurityAction action);


new System.Net.WebPermissionAttribute : System.Security.Permissions.SecurityAction ->
System.Net.WebPermissionAttribute

Parameters
action SecurityAction SecurityAction
One of the SecurityAction values.
Exceptions
ArgumentException ArgumentException
action is not a valid SecurityAction value.

Examples
The following example demonstrates how to apply WebPermissionAttribute to a method.

// Set the declarative security for the URI.


[WebPermission(SecurityAction.Deny, Connect = @"http://www.contoso.com/")]
public void Connect()
{
// Throw an exception.
try
{
HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create("http://www.contoso.com/");
}
catch(Exception e)
{
Console.WriteLine("Exception : " + e.ToString());
}

Remarks
The SecurityAction value passed to this constructor specifies the allowable security actions that can be performed on
this class.
WebProxy WebProxy Class
Contains HTTP proxy settings for the WebRequest class.

D eclaration
[System.Serializable]
public class WebProxy : System.Runtime.Serialization.ISerializable
type WebProxy = class
interface ISerializable
interface IWebProxy

I nheritance H ierarchy
Object Object

Remarks
The WebProxy class contains the proxy settings that WebRequest instances use to determine whether a Web proxy is
used to send requests. Global Web proxy settings can be specified in machine and application configuration files, and
applications can use instances of the WebProxy class to customize Web proxy use. The WebProxy class is the base
implementation of the IWebProxy interface.
To obtain instances of the Web proxy class, you can use any of the following methods:
The WebProxy constructor.
The GetDefaultProxy method.
The Select method.
These methods each supply a WebProxy instance that you can further customize; the difference between them is how
the instance is initialized before it is returned to your application. The WebProxy constructor returns an instance of the
WebProxy class with the Address property set to null . When a request uses a WebProxy instance in this state, no
proxy is used to send the request.
The GetDefaultProxy method returns an instance of the WebProxy class with the Address, BypassProxyOnLocal, and
BypassList properties set to the values used by Internet Explorer 5.5 and later.
The Select method returns an instance of the WebProxy class with it properties set according to a combination of
Internet Explorer and configuration file settings.
The WebProxy class supports automatic detection and execution of proxy configuration scripts. This feature is also
known as Web Proxy Auto-Discovery (WPAD ). When using automatic proxy configuration, a configuration script,
typically named Wpad.dat, must be located, downloaded, compiled, and run. If these operations are successful, the
script returns the proxies that can be used for a request.

Constructors
WebProxy()
WebProxy()

Initializes an empty instance of the WebProxy class.

WebProxy(String)
WebProxy(String)

Initializes a new instance of the WebProxy class with the specified URI.

WebProxy(Uri)
WebProxy(Uri)

Initializes a new instance of the WebProxy class from the specified Uri instance.

WebProxy(SerializationInfo, StreamingContext)
WebProxy(SerializationInfo, StreamingContext)

Initializes an instance of the WebProxy class using previously serialized content.

WebProxy(String, Boolean)
WebProxy(String, Boolean)

Initializes a new instance of the WebProxy class with the specified URI and bypass setting.

WebProxy(String, Int32)
WebProxy(String, Int32)

Initializes a new instance of the WebProxy class with the specified host and port number.

WebProxy(Uri, Boolean)
WebProxy(Uri, Boolean)

Initializes a new instance of the WebProxy class with the Uri instance and bypass setting.

WebProxy(String, Boolean, String[])


WebProxy(String, Boolean, String[])

Initializes a new instance of the WebProxy class with the specified URI, bypass setting, and list of URIs to bypass.

WebProxy(Uri, Boolean, String[])


WebProxy(Uri, Boolean, String[])

Initializes a new instance of the WebProxy class with the specified Uri instance, bypass setting, and list of URIs to
bypass.

WebProxy(String, Boolean, String[], ICredentials)


WebProxy(String, Boolean, String[], ICredentials)

Initializes a new instance of the WebProxy class with the specified URI, bypass setting, list of URIs to bypass, and
credentials.
WebProxy(Uri, Boolean, String[], ICredentials)
WebProxy(Uri, Boolean, String[], ICredentials)

Initializes a new instance of the WebProxy class with the specified Uri instance, bypass setting, list of URIs to
bypass, and credentials.

Properties
Address
Address

Gets or sets the address of the proxy server.

BypassArrayList
BypassArrayList

Gets a list of addresses that do not use the proxy server.

BypassList
BypassList

Gets or sets an array of addresses that do not use the proxy server.

BypassProxyOnLocal
BypassProxyOnLocal

Gets or sets a value that indicates whether to bypass the proxy server for local addresses.

Credentials
Credentials

Gets or sets the credentials to submit to the proxy server for authentication.

UseDefaultCredentials
UseDefaultCredentials

Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

Methods
CreateDefaultProxy()
CreateDefaultProxy()

GetDefaultProxy()
GetDefaultProxy()

Reads the Internet Explorer nondynamic proxy settings.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data that is needed to serialize the target object.

GetProxy(Uri)
GetProxy(Uri)

Returns the proxied URI for a request.

IsBypassed(Uri)
IsBypassed(Uri)

Indicates whether to use the proxy server for the specified host.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Creates the serialization data and context that are used by the system to serialize a WebProxy object.
WebProxy.Address WebProxy.Address
I n this Article
Gets or sets the address of the proxy server.
public Uri Address { get; set; }
member this.Address : Uri with get, set

Returns
Uri Uri
A Uri instance that contains the address of the proxy server.

Examples
The following code example displays the properties of a WebProxy object, including its Address.
// The following method displays the properties of the
// specified WebProxy instance.

public static void DisplayProxyProperties(WebProxy proxy)


{
Console.WriteLine("Address: {0}", proxy.Address);
Console.WriteLine( "Bypass on local: {0}", proxy.BypassProxyOnLocal );

int count = proxy.BypassList.Length;


if (count == 0)
{
Console.WriteLine("The bypass list is empty.");
return;
}
string[] bypass = proxy.BypassList;
Console.WriteLine("The bypass list contents:");

for (int i=0; i< count; i++)


{
Console.WriteLine(bypass[i]);
}
}

Remarks
The Address property contains the address of the proxy server. When automatic proxy detection is not enabled, and no
automatic configuration script is specified, the Address property and BypassList determine the proxy used for a
request.
When the Address property is null , requests bypass the proxy and connect directly to the destination host.
WebProxy.BypassArrayList WebProxy.BypassArrayList
I n this Article
Gets a list of addresses that do not use the proxy server.
public System.Collections.ArrayList BypassArrayList { get; }
member this.BypassArrayList : System.Collections.ArrayList

Returns
ArrayList ArrayList
An ArrayList that contains a list of BypassList arrays that represents URIs that do not use the proxy server when
accessed.

Remarks
The BypassList is an array list of regular expression strings that describe the URIs that a WebRequest instance accesses
directly instead of through the proxy server.
WebProxy.BypassList WebProxy.BypassList
I n this Article
Gets or sets an array of addresses that do not use the proxy server.
public string[] BypassList { get; set; }
member this.BypassList : string[] with get, set

Returns
String[]
An array that contains a list of regular expressions that describe URIs that do not use the proxy server when accessed.

Examples
The following code example displays the properties of a WebProxy object, including its BypassList property.
// The following method displays the properties of the
// specified WebProxy instance.

public static void DisplayProxyProperties(WebProxy proxy)


{
Console.WriteLine("Address: {0}", proxy.Address);
Console.WriteLine( "Bypass on local: {0}", proxy.BypassProxyOnLocal );

int count = proxy.BypassList.Length;


if (count == 0)
{
Console.WriteLine("The bypass list is empty.");
return;
}
string[] bypass = proxy.BypassList;
Console.WriteLine("The bypass list contents:");

for (int i=0; i< count; i++)


{
Console.WriteLine(bypass[i]);
}
}

Remarks
The BypassList property contains an array of regular expressions that describe URIs that a WebRequest instance
accesses directly instead of through the proxy server.
WebProxy.BypassProxyOnLocal WebProxy.BypassProxyOn
Local
I n this Article
Gets or sets a value that indicates whether to bypass the proxy server for local addresses.

public bool BypassProxyOnLocal { get; set; }


member this.BypassProxyOnLocal : bool with get, set

Returns
Boolean Boolean
true to bypass the proxy server for local addresses; otherwise, false . The default value is false .

Examples
The following code example demonstrates calling a constructor that sets this property and getting the value of this
property.
public static WebProxy CreateProxyWithHostAddress(bool bypassLocal)
{
WebProxy proxy = new WebProxy("http://contoso", bypassLocal);
Console.WriteLine("Bypass proxy for local URIs?: {0}",
proxy.BypassProxyOnLocal);
return proxy;
}

Remarks
The setting of the BypassProxyOnLocal property determines whether WebRequest instances use the proxy server
when accessing local Internet resources.
If BypassProxyOnLocal is true , requests to local Internet resources do not use the proxy server. Local requests are
identified by the lack of a period (.) in the URI, as in http://webserver/, or access the local server, including
http://localhost, http://loopback, or http://127.0.0.1. When BypassProxyOnLocal is false , all Internet requests are
made through the proxy server.
Note

Requests to a local host with a URI that contain a period use the proxy. To avoid using a proxy in these cases, create an
entry for the host in the BypassList.
WebProxy.CreateDefaultProxy WebProxy.CreateDefault
Proxy
I n this Article
public static System.Net.IWebProxy CreateDefaultProxy ();
static member CreateDefaultProxy : unit -> System.Net.IWebProxy

Returns
IWebProxy IWebProxy
WebProxy.Credentials WebProxy.Credentials
I n this Article
Gets or sets the credentials to submit to the proxy server for authentication.
public System.Net.ICredentials Credentials { get; set; }
member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials instance that contains the credentials to submit to the proxy server for authentication.
Exceptions
InvalidOperationException InvalidOperationException
You attempted to set this property when the UseDefaultCredentials property was set to true .

Remarks
The Credentials property contains the authentication credentials to send to the proxy server in response to an HTTP
407 (proxy authorization) status code. In most client scenarios, you should use the DefaultCredentials, which are the
credentials of the currently logged on user. To do this, set the UseDefaultCredentials property to true instead of
setting this property.
Note

If you set the Credentials property to credentials other than the DefaultCredentials, setting the UseDefaultCredentials
property to true causes a InvalidOperationException. To prevent this, you must set the Credentials property to null
before setting the UseDefaultCredentials property to true . Likewise, you cannot set this property to any value when
UseDefaultCredentials is true .
WebProxy.GetDefaultProxy WebProxy.GetDefaultProxy
I n this Article
Reads the Internet Explorer nondynamic proxy settings.
[System.Obsolete("This method has been deprecated. Please use the proxy selected for you by default.
http://go.microsoft.com/fwlink/?linkid=14202")]
[System.Obsolete("This method has been deprecated. Please use the proxy selected for you by default.
https://go.microsoft.com/fwlink/?linkid=14202")]
public static System.Net.WebProxy GetDefaultProxy ();
static member GetDefaultProxy : unit -> System.Net.WebProxy

Returns
WebProxy WebProxy
A WebProxy instance that contains the nondynamic proxy settings from Internet Explorer 5.5 and later.
Attributes ObsoleteAttribute ObsoleteAttribute

Examples
The following code example demonstrates calling this method.
public static void CheckDefaultProxyForRequest(Uri resource)
{
WebProxy proxy = (WebProxy) WebProxy.GetDefaultProxy();

// See what proxy is used for resource.


Uri resourceProxy = proxy.GetProxy(resource);

// Test to see whether a proxy was selected.


if (resourceProxy == resource)
{
Console.WriteLine("No proxy for {0}", resource);
}
else
{
Console.WriteLine("Proxy for {0} is {1}", resource.ToString(),
resourceProxy.ToString());
}
}

Remarks
The GetDefaultProxy method reads the nondynamic proxy settings stored by Internet Explorer 5.5 and later, and
creates a WebProxy instance with those settings.
The GetDefaultProxy method does not pick up any dynamic settings that are generated from scripts run by Internet
Explorer, from automatic configuration entries, or from DHCP or DNS lookups.
Applications should use the WebRequest.DefaultWebProxy property and the WebRequest.GetSystemWebProxy
method instead of the GetDefaultProxy method.
WebProxy.GetObjectData WebProxy.GetObjectData
I n this Article
Populates a SerializationInfo with the data that is needed to serialize the target object.
protected virtual void GetObjectData (System.Runtime.Serialization.SerializationInfo
serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
abstract member GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
WebProxy.GetProxy WebProxy.GetProxy
I n this Article
Returns the proxied URI for a request.
public Uri GetProxy (Uri destination);
abstract member GetProxy : Uri -> Uri
override this.GetProxy : Uri -> Uri

Parameters
destination Uri Uri
The Uri instance of the requested Internet resource.
Returns
Uri Uri
The Uri instance of the Internet resource, if the resource is on the bypass list; otherwise, the Uri instance of the proxy.
Exceptions
ArgumentNullException ArgumentNullException
The destination parameter is null .

Examples
The following code example creates a WebProxy object and calls this method to get the proxy that is selected for a
resource.
// The following method creates a WebProxy object that uses Internet Explorer's
// detected script if it is found in the registry; otherwise, it
// tries to use Web proxy auto-discovery to set the proxy used for
// the request.

public static void CheckAutoGlobalProxyForRequest(Uri resource)


{
WebProxy proxy = new WebProxy();

// Display the proxy's properties.


DisplayProxyProperties(proxy);

// See what proxy is used for the resource.


Uri resourceProxy = proxy.GetProxy(resource);

// Test to see whether a proxy was selected.


if (resourceProxy == resource)
{
Console.WriteLine("No proxy for {0}", resource);
}
else
{
Console.WriteLine("Proxy for {0} is {1}", resource.OriginalString,
resourceProxy.ToString());
}
}

Remarks
The GetProxy method returns the URI that the WebRequest instance uses to access the Internet resource.
GetProxy compares destination with the contents of BypassList, using the IsBypassed method. If IsBypassed returns
true , GetProxy returns destination and the WebRequest instance does not use the proxy server.

If destination is not in BypassList, the WebRequest instance uses the proxy server and the Address property is
returned.
WebProxy.IsBypassed WebProxy.IsBypassed
I n this Article
Indicates whether to use the proxy server for the specified host.
public bool IsBypassed (Uri host);
abstract member IsBypassed : Uri -> bool
override this.IsBypassed : Uri -> bool

Parameters
host Uri Uri
The Uri instance of the host to check for proxy use.
Returns
Boolean Boolean
true if the proxy server should not be used for host ; otherwise, false .
Exceptions
ArgumentNullException ArgumentNullException
The host parameter is null .

Examples
The following code example creates a WebProxy object and calls this method to check whether the bypass list is
properly set.

public static WebProxy CreateProxyAndCheckBypass(bool bypassLocal)


{
// Do not use the proxy server for Contoso.com URIs.
string[] bypassList = new string[]{";*.Contoso.com"};
WebProxy proxy = new WebProxy("http://contoso",
bypassLocal,
bypassList);

// Test the bypass list.


if (!proxy.IsBypassed(new Uri("http://www.Contoso.com")))
{
Console.WriteLine("Bypass not working!");
return null;
}
else
{
Console.WriteLine("Bypass is working.");
return proxy;
}
}

Remarks
The IsBypassed method is used to determine whether to bypass the proxy server when accessing an Internet resource.
The BypassProxyOnLocal and BypassList properties control the return value of the IsBypassed method.
IsBypassed returns true under any of the following conditions:
If BypassProxyOnLocal is true and host is a local URI. Local requests are identified by the lack of a period (.) in the
URI, as in "http://webserver/".
If host matches a regular expression in BypassList.
If Address is null .
All other conditions return false .
WebProxy.ISerializable.GetObjectData
I n this Article
Creates the serialization data and context that are used by the system to serialize a WebProxy object.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
The SerializationInfo object to populate with data.
streamingContext StreamingContext
A StreamingContext structure that indicates the destination for this serialization.

Remarks
The system calls this method to serialize an object; applications do not call it directly.
WebProxy.UseDefaultCredentials WebProxy.UseDefault
Credentials
I n this Article
Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.

public bool UseDefaultCredentials { get; set; }


member this.UseDefaultCredentials : bool with get, set

Returns
Boolean Boolean
true if the default credentials are used; otherwise, false . The default value is false .

Exceptions
InvalidOperationException InvalidOperationException
You attempted to set this property when the Credentials property contains credentials other than the default
credentials.

Remarks
Set this property to true when requests made by this WebProxy object should, if requested by the server, be
authenticated using the credentials of the currently logged on user. For client applications, this is the desired behavior
in most scenarios. For middle tier applications, such as ASP.NET applications, instead of using this property, you would
typically set the Credentials property to the credentials of the client on whose behalf the request is made.
The following table shows the effect of setting the UseDefaultCredentials value, based on the value of the Credentials
property.

CR ED ENTIALS V ALU E U S ED EFAU LTCR ED ENTIALS V ALU E EFFECT

DefaultCredentials true No effect.

DefaultCredentials false Credentials is set to null .

null true Credentials is set to DefaultCredentials.

Any value other than DefaultCredentials true or false Setting UseDefaultCredentials throws
or null an exception.

If UseDefaultCredentials is false , you can change the Credentials property to any credentials. If
UseDefaultCredentials is true , changing the Credentials property from DefaultCredentials (the value that is set when
the UseDefaultCredentials property is set to true ) will throw an exception.
WebProxy WebProxy
I n this Article

Overloads
WebProxy()
Initializes an empty instance of the WebProxy class.

WebProxy(String) WebProxy(String)
Initializes a new instance of the WebProxy class with the
specified URI.

WebProxy(Uri) WebProxy(Uri)
Initializes a new instance of the WebProxy class from the
specified Uri instance.

WebProxy(SerializationInfo, StreamingContext) WebProxy(


SerializationInfo, StreamingContext) Initializes an instance of the WebProxy class using previously
serialized content.

WebProxy(String, Boolean) WebProxy(String, Boolean)


Initializes a new instance of the WebProxy class with the
specified URI and bypass setting.

WebProxy(String, Int32) WebProxy(String, Int32)


Initializes a new instance of the WebProxy class with the
specified host and port number.

WebProxy(Uri, Boolean) WebProxy(Uri, Boolean)


Initializes a new instance of the WebProxy class with the Uri
instance and bypass setting.

WebProxy(String, Boolean, String[]) WebProxy(String, Boolean,


String[]) Initializes a new instance of the WebProxy class with the
specified URI, bypass setting, and list of URIs to bypass.

WebProxy(Uri, Boolean, String[]) WebProxy(Uri, Boolean,


String[]) Initializes a new instance of the WebProxy class with the
specified Uri instance, bypass setting, and list of URIs to
bypass.

WebProxy(String, Boolean, String[], ICredentials) WebProxy(


String, Boolean, String[], ICredentials) Initializes a new instance of the WebProxy class with the
specified URI, bypass setting, list of URIs to bypass, and
credentials.

WebProxy(Uri, Boolean, String[], ICredentials) WebProxy(Uri,


Boolean, String[], ICredentials) Initializes a new instance of the WebProxy class with the
specified Uri instance, bypass setting, list of URIs to bypass,
and credentials.

WebProxy()
WebProxy()
Initializes an empty instance of the WebProxy class.
public WebProxy ();

Examples
The following code example demonstrates calling this constructor.
public static WebProxy CreateProxy()
{
return new WebProxy();
}

Remarks
The default constructor initializes an empty instance of the WebProxy class with the Address property set to null .
When the Address property is null , the IsBypassed method returns true and the GetProxy method returns the
destination address.

WebProxy(String) WebProxy(String)
Initializes a new instance of the WebProxy class with the specified URI.

public WebProxy (string Address);


new System.Net.WebProxy : string -> System.Net.WebProxy

Parameters
Address String String
The URI of the proxy server.
Exceptions
UriFormatException UriFormatException
Address is an invalid URI.
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithHost()


{
return new WebProxy("http://contoso");
}

Remarks
The WebProxy instance is initialized with the Address property set to a Uri instance containing Address .

WebProxy(Uri) WebProxy(Uri)
Initializes a new instance of the WebProxy class from the specified Uri instance.

public WebProxy (Uri Address);


new System.Net.WebProxy : Uri -> System.Net.WebProxy
Parameters
Address Uri Uri
A Uri instance that contains the address of the proxy server.
Examples
The following code example demonstrates calling this constructor.
public static WebProxy CreateProxyWithExampleAddress()
{
return new WebProxy(new Uri("http://contoso"));
}

Remarks
The WebProxy instance is initialized with the Address property set to the Address parameter.

WebProxy(SerializationInfo, StreamingContext)
WebProxy(SerializationInfo, StreamingContext)
Initializes an instance of the WebProxy class using previously serialized content.

protected WebProxy (System.Runtime.Serialization.SerializationInfo serializationInfo,


System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.WebProxy : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.WebProxy

Parameters
serializationInfo SerializationInfo SerializationInfo
The serialization data.
streamingContext StreamingContext StreamingContext
The context for the serialized data.
Remarks
This method is called by the system to deserialize a WebProxy instance; applications do not call it.

WebProxy(String, Boolean) WebProxy(String, Boolean)


Initializes a new instance of the WebProxy class with the specified URI and bypass setting.

public WebProxy (string Address, bool BypassOnLocal);


new System.Net.WebProxy : string * bool -> System.Net.WebProxy

Parameters
Address String String
The URI of the proxy server.
BypassOnLocal Boolean Boolean
true to bypass the proxy for local addresses; otherwise, false .
Exceptions
UriFormatException UriFormatException
Address is an invalid URI.
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithHostAddress(bool bypassLocal)


{
WebProxy proxy = new WebProxy("http://contoso", bypassLocal);
Console.WriteLine("Bypass proxy for local URIs?: {0}",
proxy.BypassProxyOnLocal);
return proxy;
}

Remarks
The WebProxy instance is initialized with the Address property set to a Uri instance that contains Address and the
BypassProxyOnLocal property set to BypassOnLocal .

See BypassProxyOnLocalBypassProxyOnLocal
Also

WebProxy(String, Int32) WebProxy(String, Int32)


Initializes a new instance of the WebProxy class with the specified host and port number.

public WebProxy (string Host, int Port);


new System.Net.WebProxy : string * int -> System.Net.WebProxy

Parameters
Host String String
The name of the proxy host.
Port Int32 Int32
The port number on Host to use.

Exceptions
UriFormatException UriFormatException
The URI formed by combining Host and Port is not a valid URI.
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithHostAndPort()


{
return new WebProxy("http://contoso", 80);
}

Remarks
The WebProxy instance is initialized with the Address property set to a Uri instance of the form http:// Host : Port .
WebProxy(Uri, Boolean) WebProxy(Uri, Boolean)
Initializes a new instance of the WebProxy class with the Uri instance and bypass setting.

public WebProxy (Uri Address, bool BypassOnLocal);


new System.Net.WebProxy : Uri * bool -> System.Net.WebProxy

Parameters
Address Uri Uri
A Uri instance that contains the address of the proxy server.
BypassOnLocal Boolean Boolean
true to bypass the proxy for local addresses; otherwise, false .
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithExampleAddress(bool bypassLocal)


{
return new WebProxy(new Uri("http://contoso"), bypassLocal);
}

Remarks
The WebProxy instance is initialized with the Address property set to Address and with the BypassProxyOnLocal
property set to BypassOnLocal .

WebProxy(String, Boolean, String[]) WebProxy(String, Boolean,


String[])
Initializes a new instance of the WebProxy class with the specified URI, bypass setting, and list of URIs to bypass.

public WebProxy (string Address, bool BypassOnLocal, string[] BypassList);


new System.Net.WebProxy : string * bool * string[] -> System.Net.WebProxy

Parameters
Address String String
The URI of the proxy server.
BypassOnLocal Boolean Boolean
true to bypass the proxy for local addresses; otherwise, false .

BypassList String[]
An array of regular expression strings that contain the URIs of the servers to bypass.
Exceptions
UriFormatException UriFormatException
Address is an invalid URI.
Examples
The following code example demonstrates calling this constructor.
public static WebProxy CreateProxyWithHostAndBypassList(bool bypassLocal)
{
// Do not use the proxy server for Contoso.com URIs.
string[] bypassList = new string[]{";*.Contoso.com"};
return new WebProxy("http://contoso",
bypassLocal,
bypassList);
}

Remarks
The WebProxy instance is initialized with the Address property set to a Uri instance that contains Address , the
BypassProxyOnLocal property set to BypassOnLocal , and the BypassList property set to BypassList .

See BypassProxyOnLocalBypassProxyOnLocal
Also BypassListBypassList

WebProxy(Uri, Boolean, String[]) WebProxy(Uri, Boolean, String[])


Initializes a new instance of the WebProxy class with the specified Uri instance, bypass setting, and list of URIs to
bypass.

public WebProxy (Uri Address, bool BypassOnLocal, string[] BypassList);


new System.Net.WebProxy : Uri * bool * string[] -> System.Net.WebProxy

Parameters
Address Uri Uri
A Uri instance that contains the address of the proxy server.
BypassOnLocal Boolean Boolean
true to bypass the proxy for local addresses; otherwise, false .

BypassList String[]
An array of regular expression strings that contains the URIs of the servers to bypass.
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithBypassList(bool bypassLocal)


{
// Do not use the proxy server for Contoso.com URIs.
string[] bypassList = new string[]{";*.Contoso.com"};
return new WebProxy(new Uri("http://contoso"),
bypassLocal,
bypassList);
}

Remarks
The WebProxy instance is initialized with the Address property set to Address , the BypassProxyOnLocal property set
to BypassOnLocal , and the BypassList property set to BypassList .

WebProxy(String, Boolean, String[], ICredentials)


WebProxy(String, Boolean, String[], ICredentials)
Initializes a new instance of the WebProxy class with the specified URI, bypass setting, list of URIs to bypass, and
credentials.

public WebProxy (string Address, bool BypassOnLocal, string[] BypassList, System.Net.ICredentials


Credentials);
new System.Net.WebProxy : string * bool * string[] * System.Net.ICredentials -> System.Net.WebProxy

Parameters
Address String String
The URI of the proxy server.
BypassOnLocal Boolean Boolean
true to bypass the proxy for local addresses; otherwise, false .

BypassList String[]
An array of regular expression strings that contains the URIs of the servers to bypass.
Credentials ICredentials ICredentials
An ICredentials instance to submit to the proxy server for authentication.
Exceptions
UriFormatException UriFormatException
Address is an invalid URI.
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithCredentials(bool bypassLocal)


{
// Do not use the proxy server for Contoso.com URIs.
string[] bypassList = new string[]{";*.Contoso.com"};
return new WebProxy("http://contoso",
bypassLocal,
bypassList,
CredentialCache.DefaultCredentials);
}

Remarks
The WebProxy instance is initialized with the Address property set to a Uri instance that contains Address , the
BypassProxyOnLocal property set to BypassOnLocal , the BypassList property set to BypassList , and the Credentials
property set to Credentials .
See BypassProxyOnLocalBypassProxyOnLocal
Also BypassListBypassList

WebProxy(Uri, Boolean, String[], ICredentials) WebProxy(Uri,


Boolean, String[], ICredentials)
Initializes a new instance of the WebProxy class with the specified Uri instance, bypass setting, list of URIs to bypass,
and credentials.

public WebProxy (Uri Address, bool BypassOnLocal, string[] BypassList, System.Net.ICredentials


Credentials);
new System.Net.WebProxy : Uri * bool * string[] * System.Net.ICredentials -> System.Net.WebProxy

Parameters
Address Uri Uri
A Uri instance that contains the address of the proxy server.
BypassOnLocal Boolean Boolean
true to bypass the proxy for local addresses; otherwise, false .
BypassList String[]
An array of regular expression strings that contains the URIs of the servers to bypass.
Credentials ICredentials ICredentials
An ICredentials instance to submit to the proxy server for authentication.
Examples
The following code example demonstrates calling this constructor.

public static WebProxy CreateProxyWithCredentials2(bool bypassLocal)


{
// Do not use the proxy server for Contoso.com URIs.
string[] bypassList = new string[]{";*.Contoso.com"};
return new WebProxy(new Uri("http://contoso"),
bypassLocal,
bypassList,
CredentialCache.DefaultCredentials);
}

Remarks
The WebProxy instance is initialized with the Address property set to Address , the BypassProxyOnLocal property set
to BypassOnLocal , the BypassList property set to BypassList , and the Credentials property set to Credentials .
WebRequest WebRequest Class
Makes a request to a Uniform Resource Identifier (URI). This is an abstract class.

D eclaration
[System.Serializable]
public abstract class WebRequest : MarshalByRefObject,
System.Runtime.Serialization.ISerializable
type WebRequest = class
inherit MarshalByRefObject
interface ISerializable

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject

Remarks
Im p o rt a nt

We don't recommend that you use WebRequest or its derived classes for new development. Instead, use the
System.Net.Http.HttpClient class.
WebRequest is the abstract base class for .NET's request/response model for accessing data from the Internet. An
application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in
which the application works with instances of the WebRequest class while protocol-specific descendant classes carry
out the details of the request.
Requests are sent from an application to a particular URI, such as a Web page on a server. The URI determines the
proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest
descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle
a request to a specific server or path on a server.
The WebRequest class throws a WebException when errors occur while accessing an Internet resource. The Status
property is one of the WebExceptionStatus values that indicates the source of the error. When Status is
WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet
resource.
Because the WebRequest class is an abstract class, the actual behavior of WebRequest instances at run time is
determined by the descendant class returned by Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
Note

Use the Create method to initialize new WebRequest instances. Do not use the WebRequest constructor.
Note

If the application that creates the WebRequest object runs with the credentials of a Normal user, the application will not
be able to access certificates installed in the local machine store unless permission has been explicitly given to the user
to do so.

Constructors
WebRequest()
WebRequest()
Initializes a new instance of the WebRequest class.

WebRequest(SerializationInfo, StreamingContext)
WebRequest(SerializationInfo, StreamingContext)

Initializes a new instance of the WebRequest class from the specified instances of the SerializationInfo and
StreamingContext classes.

Properties
AuthenticationLevel
AuthenticationLevel

Gets or sets values indicating the level of authentication and impersonation used for this request.

CachePolicy
CachePolicy

Gets or sets the cache policy for this request.

ConnectionGroupName
ConnectionGroupName

When overridden in a descendant class, gets or sets the name of the connection group for the request.

ContentLength
ContentLength

When overridden in a descendant class, gets or sets the content length of the request data being sent.

ContentType
ContentType

When overridden in a descendant class, gets or sets the content type of the request data being sent.

CreatorInstance
CreatorInstance

When overridden in a descendant class, gets the factory object derived from the IWebRequestCreate class used to
create the WebRequest instantiated for making the request to the specified URI.

Credentials
Credentials

When overridden in a descendant class, gets or sets the network credentials used for authenticating the request
with the Internet resource.

DefaultCachePolicy
DefaultCachePolicy

Gets or sets the default cache policy for this request.

DefaultWebProxy
DefaultWebProxy

Gets or sets the global HTTP proxy.

Headers
Headers

When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the
request.

ImpersonationLevel
ImpersonationLevel

Gets or sets the impersonation level for the current request.

Method
Method

When overridden in a descendant class, gets or sets the protocol method to use in this request.

PreAuthenticate
PreAuthenticate

When overridden in a descendant class, indicates whether to pre-authenticate the request.

Proxy
Proxy

When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.

RequestUri
RequestUri

When overridden in a descendant class, gets the URI of the Internet resource associated with the request.
Timeout
Timeout

Gets or sets the length of time, in milliseconds, before the request times out.

UseDefaultCredentials
UseDefaultCredentials

When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are
sent with requests.

Methods
Abort()
Abort()

Aborts the request.

BeginGetRequestStream(AsyncCallback, Object)
BeginGetRequestStream(AsyncCallback, Object)

When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method.

BeginGetResponse(AsyncCallback, Object)
BeginGetResponse(AsyncCallback, Object)

When overridden in a descendant class, begins an asynchronous request for an Internet resource.

Create(String)
Create(String)

Initializes a new WebRequest instance for the specified URI scheme.

Create(Uri)
Create(Uri)

Initializes a new WebRequest instance for the specified URI scheme.

CreateDefault(Uri)
CreateDefault(Uri)

Initializes a new WebRequest instance for the specified URI scheme.

CreateHttp(String)
CreateHttp(String)
Initializes a new HttpWebRequest instance for the specified URI string.

CreateHttp(Uri)
CreateHttp(Uri)

Initializes a new HttpWebRequest instance for the specified URI.

EndGetRequestStream(IAsyncResult)
EndGetRequestStream(IAsyncResult)

When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

EndGetResponse(IAsyncResult)
EndGetResponse(IAsyncResult)

When overridden in a descendant class, returns a WebResponse.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo with the data needed to serialize the target object.

GetRequestStream()
GetRequestStream()

When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

GetRequestStreamAsync()
GetRequestStreamAsync()

When overridden in a descendant class, returns a Stream for writing data to the Internet resource as an
asynchronous operation.

GetResponse()
GetResponse()

When overridden in a descendant class, returns a response to an Internet request.

GetResponseAsync()
GetResponseAsync()

When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.
GetSystemWebProxy()
GetSystemWebProxy()

Returns a proxy configured with the Internet Explorer settings of the currently impersonated user.

RegisterPortableWebRequestCreator(IWebRequestCreate)
RegisterPortableWebRequestCreator(IWebRequestCreate)

Register an IWebRequestCreate object.

RegisterPrefix(String, IWebRequestCreate)
RegisterPrefix(String, IWebRequestCreate)

Registers a WebRequest descendant for the specified URI.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the
WebRequest.

See Also
HttpWebRequest HttpWebRequest
HttpWebRequest HttpWebRequest
HttpWebRequest HttpWebRequest
WebRequest.Abort WebRequest.Abort
I n this Article
Aborts the request.
public virtual void Abort ();
abstract member Abort : unit -> unit
override this.Abort : unit -> unit

Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Remarks
The Abort method cancels asynchronous requests to Internet resources started with the BeginGetResponse method.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.AuthenticationLevel WebRequest.
AuthenticationLevel
I n this Article
Gets or sets values indicating the level of authentication and impersonation used for this request.

public System.Net.Security.AuthenticationLevel AuthenticationLevel { get; set; }


member this.AuthenticationLevel : System.Net.Security.AuthenticationLevel with get, set

Returns
AuthenticationLevel AuthenticationLevel
A bitwise combination of the AuthenticationLevel values. The default value is MutualAuthRequested.
In mutual authentication, both the client and server present credentials to establish their identity. The
MutualAuthRequired and MutualAuthRequested values are relevant for Kerberos authentication. Kerberos
authentication can be supported directly, or can be used if the Negotiate security protocol is used to select the actual
security protocol. For more information about authentication protocols, see Internet Authentication.
To determine whether mutual authentication occurred, check the IsMutuallyAuthenticated property.
If you specify the MutualAuthRequired authentication flag value and mutual authentication does not occur, your
application will receive an IOException with a ProtocolViolationException inner exception indicating that mutual
authentication failed.

Examples
The following code example sets the value of this property.

// The following example uses the System, System.Net,


// and System.IO namespaces.

public static void RequestMutualAuth(Uri resource)


{
// Create a new HttpWebRequest object for the specified resource.
WebRequest request=(WebRequest) WebRequest.Create(resource);
// Request mutual authentication.
request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;
// Supply client credentials.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// Determine whether mutual authentication was used.
Console.WriteLine("Is mutually authenticated? {0}", response.IsMutuallyAuthenticated);
// Read and display the response.
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream objects.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse.
response.Close();
}
WebRequest.BeginGetRequestStream WebRequest.Begin
GetRequestStream
I n this Article
When overridden in a descendant class, provides an asynchronous version of the GetRequestStream() method.

public virtual IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state);


abstract member BeginGetRequestStream : AsyncCallback * obj -> IAsyncResult
override this.BeginGetRequestStream : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
The AsyncCallback delegate.
state Object Object
An object containing state information for this asynchronous request.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that references the asynchronous request.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example uses the BeginGetRequestStream to asynchronously obtain the request stream.
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the request state of the request.
public WebRequest request;
public RequestState()
{
request = null;
}
}

class WebRequest_BeginGetRequeststream
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
static void Main()
{
// Create a new request to the mentioned URL.
WebRequest myWebRequest= WebRequest.Create("http://www.contoso.com");

// Create an instance of the RequestState and assign


// 'myWebRequest' to it's request field.
// 'myWebRequest' to it's request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myWebRequest;
myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'Method' property to 'POST' to post data to a Uri.


myRequestState.request.Method="POST";
// Start the Asynchronous 'BeginGetRequestStream' method call.
IAsyncResult r=(IAsyncResult) myWebRequest.BeginGetRequestStream(
new AsyncCallback(ReadCallback),myRequestState);
// Pause the current thread until the async operation completes.
Console.WriteLine("main thread waiting...");
allDone.WaitOne();
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse = myWebRequest.GetResponse();
Console.WriteLine("The string has been posted.");
Console.WriteLine("Please wait for the response...");

Stream streamResponse = myWebResponse.GetResponseStream();


StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of the HTML page are ");

while (count > 0)


{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}

// Close the Stream Object.


streamResponse.Close();
streamRead.Close();

// Release the HttpWebResponse Resource.


myWebResponse.Close();
}
private static void ReadCallback(IAsyncResult asynchronousResult)
{
RequestState myRequestState =(RequestState) asynchronousResult.AsyncState;
WebRequest myWebRequest = myRequestState.request;

// End the Asynchronus request.


Stream streamResponse = myWebRequest.EndGetRequestStream(asynchronousResult);

// Create a string that is to be posted to the uri.


Console.WriteLine("Please enter a string to be posted:");
string postData = Console.ReadLine();
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Write the data to the stream.


streamResponse.Write(byteArray,0,postData.Length);
streamResponse.Close();
allDone.Set();
}
}

Remarks
The BeginGetRequestStream method starts an asynchronous request for a stream used to send data to an Internet
resource. The callback method that implements the AsyncCallback delegate uses the EndGetRequestStream method to
return the request stream.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See EndGetRequestStream(IAsyncResult)EndGetRequestStream(IAsyncResult)
Also Making Asynchronous Requests
WebRequest.BeginGetResponse WebRequest.BeginGet
Response
I n this Article
When overridden in a descendant class, begins an asynchronous request for an Internet resource.

public virtual IAsyncResult BeginGetResponse (AsyncCallback callback, object state);


abstract member BeginGetResponse : AsyncCallback * obj -> IAsyncResult
override this.BeginGetResponse : AsyncCallback * obj -> IAsyncResult

Parameters
callback AsyncCallback AsyncCallback
The AsyncCallback delegate.
state Object Object
An object containing state information for this asynchronous request.
Returns
IAsyncResult IAsyncResult
An IAsyncResult that references the asynchronous request.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example uses BeginGetResponse to asynchronously request the target resource. When the resource has
been obtained, the specified callback method will be executed.

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the state of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] bufferRead;
public WebRequest request;
public WebResponse response;
public Stream responseStream;
public RequestState()
{
bufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
responseStream = null;
}
}
}
class WebRequest_BeginGetResponse
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
static void Main()
{
try
{
// Create a new webrequest to the mentioned URL.
WebRequest myWebRequest= WebRequest.Create("http://www.contoso.com");

// Please, set the proxy to a correct value.


WebProxy proxy=new WebProxy("myproxy:80");

proxy.Credentials=new NetworkCredential("srikun","simrin123");
myWebRequest.Proxy=proxy;
// Create a new instance of the RequestState.
RequestState myRequestState = new RequestState();
// The 'WebRequest' object is associated to the 'RequestState' object.
myRequestState.request = myWebRequest;
// Start the Asynchronous call for response.
IAsyncResult asyncResult=(IAsyncResult) myWebRequest.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestState);
allDone.WaitOne();
// Release the WebResponse resource.
myRequestState.response.Close();
Console.Read();
}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// Set the State of request to asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
WebRequest myWebRequest1=myRequestState.request;
// End the Asynchronous response.
myRequestState.response = myWebRequest1.EndGetResponse(asynchronousResult);
// Read the response into a 'Stream' object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.responseStream=responseStream;
// Begin the reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousResultRead = responseStream.BeginRead(myRequestState.bufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);

}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{
// Result state is set to AsyncState.
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
Stream responseStream = myRequestState.responseStream;
int read = responseStream.EndRead( asyncResult );
// Read the contents of the HTML page and then print to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.bufferRead, 0,
read));
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.bufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
}
else
{
Console.WriteLine("
The HTML page Contents are: ");
if(myRequestState.requestData.Length>1)
{
string sringContent;
sringContent = myRequestState.requestData.ToString();
Console.WriteLine(sringContent);
}
Console.WriteLine("
Press 'Enter' key to continue........");
responseStream.Close();
allDone.Set();
}
}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : {0}" , e.Source);
Console.WriteLine("Message : {0}" , e.Message);
}

Remarks
The BeginGetResponse method starts an asynchronous request for a response. The callback method that implements
the AsyncCallback delegate uses the EndGetResponse method to return the WebResponse from the Internet resource.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
Note

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from
the server.
See EndGetResponse(IAsyncResult)EndGetResponse(IAsyncResult)
Also GetResponse()GetResponse()
Making Asynchronous Requests
WebRequest.CachePolicy WebRequest.CachePolicy
I n this Article
Gets or sets the cache policy for this request.
public virtual System.Net.Cache.RequestCachePolicy CachePolicy { get; set; }
member this.CachePolicy : System.Net.Cache.RequestCachePolicy with get, set

Returns
RequestCachePolicy RequestCachePolicy
A RequestCachePolicy object that defines a cache policy.

Examples
The following code example demonstrates setting the cache policy for a Web request.
// The following method demonstrates overriding the
// caching policy for a request.
public static WebResponse GetResponseNoCache(Uri uri)
{
// Set a default policy level for the "http:" and "https" schemes.
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
// Create the request.
WebRequest request = WebRequest.Create(uri);
// Define a cache policy for this request only.
HttpRequestCachePolicy noCachePolicy = new
HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
request.CachePolicy = noCachePolicy;
WebResponse response = request.GetResponse();
Console.WriteLine("IsFromCache? {0}", response.IsFromCache);
return response;
}

Remarks
The current cache policy and the presence of the requested resource in the cache determine whether a response can be
retrieved from the cache. Using cached responses usually improves application performance, but there is a risk that the
response in the cache does not match the response on the server.
Default cache policy can be specified in the Machine.config configuration file or by setting the DefaultCachePolicy
property for requests that use the Hypertext Transfer Protocol (HTTP ) or Secure Hypertext Transfer Protocol (HTTPS )
URI scheme.
A copy of a resource is only added to the cache if the response stream for the resource is retrieved and read to the end
of the stream. So another request for the same resource could use a cached copy, depending on the cache policy level
for this request.
See RequestCachePolicyRequestCachePolicy
Also DefaultCachePolicyDefaultCachePolicy
WebRequest.ConnectionGroupName WebRequest.
ConnectionGroupName
I n this Article
When overridden in a descendant class, gets or sets the name of the connection group for the request.

public virtual string ConnectionGroupName { get; set; }


member this.ConnectionGroupName : string with get, set

Returns
String String
The name of the connection group for the request.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Remarks
The ConnectionGroupName property associates specific requests within an application to one or more connection
pools.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See Connection Grouping
Also
WebRequest.ContentLength WebRequest.ContentLength
I n this Article
When overridden in a descendant class, gets or sets the content length of the request data being sent.
public virtual long ContentLength { get; set; }
member this.ContentLength : int64 with get, set

Returns
Int64 Int64
The number of bytes of request data being sent.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example sets the ContentLength property to the amount of bytes in the outgoing byte buffer.

// Set the 'ContentType' property of the WebRequest.


myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'ContentLength' property of the WebRequest.


myWebRequest.ContentLength=byteArray.Length;
Stream newStream=myWebRequest.GetRequestStream();
newStream.Write(byteArray,0,byteArray.Length);

// Close the Stream object.


newStream.Close();

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.


WebResponse myWebResponse=myWebRequest.GetResponse();

Remarks
The ContentLength property contains the number of bytes of data sent to the Internet resource by the WebRequest
instance.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.ContentType WebRequest.ContentType
I n this Article
When overridden in a descendant class, gets or sets the content type of the request data being sent.
public virtual string ContentType { get; set; }
member this.ContentType : string with get, set

Returns
String String
The content type of the request data.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example sets the ContentType property to the appropriate media type.

// Set the 'ContentType' property of the WebRequest.


myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'ContentLength' property of the WebRequest.


myWebRequest.ContentLength=byteArray.Length;
Stream newStream=myWebRequest.GetRequestStream();
newStream.Write(byteArray,0,byteArray.Length);

// Close the Stream object.


newStream.Close();

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.


WebResponse myWebResponse=myWebRequest.GetResponse();

Remarks
The ContentType property contains the media type of the request. This is typically the MIME encoding of the content.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.Create WebRequest.Create
I n this Article

Overloads
Create(String) Create(String)
Initializes a new WebRequest instance for the specified URI
scheme.

Create(Uri) Create(Uri)
Initializes a new WebRequest instance for the specified URI
scheme.

Create(String) Create(String)
Initializes a new WebRequest instance for the specified URI scheme.
public static System.Net.WebRequest Create (string requestUriString);
static member Create : string -> System.Net.WebRequest

Parameters
requestUriString String String
The URI that identifies the Internet resource.
Returns
WebRequest WebRequest
A WebRequest descendant for the specific URI scheme.
Exceptions
NotSupportedException NotSupportedException
The request scheme specified in requestUriString has not been registered.
ArgumentNullException ArgumentNullException
requestUriString is null .
SecurityException SecurityException
The caller does not have WebPermissionAttribute permission to connect to the requested URI or a URI that the
request is redirected to.
UriFormatException UriFormatException
In the .NET for Windows Store apps or the Portable Class Library, catch the base class exception, FormatException,
instead.
The URI specified in requestUriString is not a valid URI.
Examples
The following example uses Create to instantiate an HttpWebRequest instance. A string representing the target URL is
used as the constructor parameter.
Uri ourUri = new Uri(url);

// Create a 'WebRequest' object with the specified url.


WebRequest myWebRequest = WebRequest.Create(url);

// Send the 'WebRequest' and wait for response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Use "ResponseUri" property to get the actual Uri from where the response was attained.
if (ourUri.Equals(myWebResponse.ResponseUri))
Console.WriteLine("
Request Url : {0} was not redirected",url);
else
Console.WriteLine("
Request Url : {0} was redirected to {1}",url,myWebResponse.ResponseUri);
// Release resources of response object.
myWebResponse.Close();

Remarks
The Create method returns a descendant of the WebRequest class determined at run time as the closest registered
match for requestUri .

For example, when a URI beginning with http:// or https:// is passed in requestUri , an HttpWebRequest is
returned by Create. If a URI beginning with ftp:// is passed instead, the Create method will return a FtpWebRequest
instance. If a URI beginning with file:// is passed instead, the Create method will return a FileWebRequest instance.
The pre-registered reserve types already registered include the following:
http://

https://

ftp://

file://

.NET includes support for the http:// , https:// , ftp:// , and file:// URI schemes. Custom WebRequest
descendants to handle other requests are registered with the RegisterPrefix method.
The Create method uses the requestUriString parameter to create a Uri instance that it passes to the new
WebRequest.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
See Programming Pluggable Protocols
Also

Create(Uri) Create(Uri)
Initializes a new WebRequest instance for the specified URI scheme.
public static System.Net.WebRequest Create (Uri requestUri);
static member Create : Uri -> System.Net.WebRequest

Parameters
requestUri Uri Uri
A Uri containing the URI of the requested resource.
Returns
WebRequest WebRequest
A WebRequest descendant for the specified URI scheme.
Exceptions
NotSupportedException NotSupportedException
The request scheme specified in requestUri is not registered.

ArgumentNullException ArgumentNullException
requestUri is null .

SecurityException SecurityException
The caller does not have WebPermissionAttribute permission to connect to the requested URI or a URI that the
request is redirected to.
Examples
The following example uses Create to instantiate an HttpWebRequest instance. A Uri representing the target URL is
used as the constructor parameter.
// Create a new 'Uri' object with the specified string.
Uri myUri =new Uri("http://www.contoso.com");
// Create a new request to the above mentioned URL.
WebRequest myWebRequest= WebRequest.Create(myUri);
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse= myWebRequest.GetResponse();

Remarks
The Create method returns a descendant of the WebRequest class determined at run time as the closest registered
match for requestUri .

For example, if you create a WebRequest descendant, Handler1, to handle requests to http://www.contoso.com/text/
and another named Handler2 to handle requests to http://www.contoso.com/code/ , you can use Create method to
return the WebRequest descendant associated with either specified URI.
To return a descendant of the WebRequest class based on only the scheme portion of a URI, use the CreateDefault
method.
For example, when a URI beginning with http:// or https:// is passed in requestUri , an HttpWebRequest is
returned by Create. If a URI beginning with ftp:// is passed instead, the Create method will return a FileWebRequest
instance. If a URI beginning with file:// is passed instead, the Create method will return a FileWebRequest instance.

The pre-registered reserve types already registered include the following:


http://

https://

ftp://

file://
.NET includes support for the http:// , https:// , ftp:// , and file:// URI schemes. Custom WebRequest
descendants to handle other requests are registered with the RegisterPrefix method.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebRequest.CreateDefault WebRequest.CreateDefault
I n this Article
Initializes a new WebRequest instance for the specified URI scheme.
public static System.Net.WebRequest CreateDefault (Uri requestUri);
static member CreateDefault : Uri -> System.Net.WebRequest

Parameters
requestUri Uri Uri
A Uri containing the URI of the requested resource.
Returns
WebRequest WebRequest
A WebRequest descendant for the specified URI scheme.
Exceptions
NotSupportedException NotSupportedException
The request scheme specified in requestUri is not registered.
ArgumentNullException ArgumentNullException
requestUri is null .
SecurityException SecurityException
The caller does not have WebPermissionAttribute permission to connect to the requested URI or a URI that the
request is redirected to.

Remarks
The CreateDefault method returns a WebRequest descendant instance based on only the scheme portion of a URI.
For example, when a URI beginning with http:// is passed in requestUri , an HttpWebRequest is returned by
CreateDefault. If a URI beginning with file:// is passed instead, the CreateDefault method will return a
FileWebRequest.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in .NET.
WebRequest.CreateHttp WebRequest.CreateHttp
I n this Article

Overloads
CreateHttp(String) CreateHttp(String)
Initializes a new HttpWebRequest instance for the specified
URI string.

CreateHttp(Uri) CreateHttp(Uri)
Initializes a new HttpWebRequest instance for the specified
URI.

CreateHttp(String) CreateHttp(String)
Initializes a new HttpWebRequest instance for the specified URI string.
public static System.Net.HttpWebRequest CreateHttp (string requestUriString);
static member CreateHttp : string -> System.Net.HttpWebRequest

Parameters
requestUriString String String
A URI string that identifies the Internet resource.
Returns
HttpWebRequest HttpWebRequest
An HttpWebRequest instance for the specific URI string.
Exceptions
NotSupportedException NotSupportedException
The request scheme specified in requestUriString is the http or https scheme.
ArgumentNullException ArgumentNullException
requestUriString is null .
SecurityException SecurityException
The caller does not have WebPermissionAttribute permission to connect to the requested URI or a URI that the
request is redirected to.
UriFormatException UriFormatException
The URI specified in requestUriString is not a valid URI.
Remarks
The CreateHttp(String) method returns an instance of the HttpWebRequest class for the requestUriString .
When a URI that begins with http:// or https:// is passed in the requestUriString parameter, a HttpWebRequest
is returned by CreateHttp(String). Any other scheme will throw a NotSupportedException.
The CreateHttp(String) method uses the requestUriString parameter to create a Uri instance that it passes to the
new HttpWebRequest. If the method is successful, the AllowReadStreamBuffering property on the returned
HttpWebRequest instance is set to false .
.NET includes support for the http:// and https:// URI schemes. Custom WebRequest descendants to handle other
requests are registered with the RegisterPrefix method. The Create(String) method can be used to create a descendant
of the WebRequest class for other schemes.

CreateHttp(Uri) CreateHttp(Uri)
Initializes a new HttpWebRequest instance for the specified URI.

public static System.Net.HttpWebRequest CreateHttp (Uri requestUri);


static member CreateHttp : Uri -> System.Net.HttpWebRequest

Parameters
requestUri Uri Uri
A URI that identifies the Internet resource.
Returns
HttpWebRequest HttpWebRequest
An HttpWebRequest instance for the specific URI string.
Exceptions
NotSupportedException NotSupportedException
The request scheme specified in requestUri is the http or https scheme.
ArgumentNullException ArgumentNullException
requestUri is null .
SecurityException SecurityException
The caller does not have WebPermissionAttribute permission to connect to the requested URI or a URI that the
request is redirected to.
UriFormatException UriFormatException
The URI specified in requestUri is not a valid URI.
Remarks
The CreateHttp(Uri) method returns an instance of the HttpWebRequest class for the requestUri .
When a URI that begins with http:// or http:// is passed in the requestUri parameter, an HttpWebRequest is
returned by CreateHttp(Uri). Another other scheme will throw a NotSupportedException.
The CreateHttp(Uri) method uses the requestUri parameter to create a new HttpWebRequest instance. If the method
is successful, the AllowReadStreamBuffering property on the returned HttpWebRequest instance is set to false .
.NET includes support for the http:// and https:// URI schemes. Custom WebRequest descendants to handle other
requests are registered with the RegisterPrefix method. The Create(Uri) method can be used to create a descendant of
the WebRequest class for other schemes.
WebRequest.CreatorInstance WebRequest.Creator
Instance
I n this Article
When overridden in a descendant class, gets the factory object derived from the IWebRequestCreate class used to
create the WebRequest instantiated for making the request to the specified URI.
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public virtual System.Net.IWebRequestCreate CreatorInstance { get; }
member this.CreatorInstance : System.Net.IWebRequestCreate

Returns
IWebRequestCreate IWebRequestCreate
The derived WebRequest type returned by the Create(Uri) method.
Attributes ObsoleteAttribute

Remarks
This property allows an application to determine which IWebRequestCreate derived factory object was used to create
the request. This object may be System.Net.Browser.WebRequestCreator.BrowserHttp or
System.Net.Browser.WebRequestCreator.ClientHttp, but it may also be a custom instance derived from
IWebRequestCreate. This allows an application to determine whether the browser hosting Silverlight, the Silverlight
client, or some custom object handles HTTP requests and responses for the WebRequest instance. The RegisterPrefix
method allows an application to configure which derived WebRequest type will be instantiated when making a request
to a specific URI. WebRequest creators are typically registered to handle a specific protocol, such HTTP or HTTPS, but
can be registered to handle a request to a specific server or path on a server. This is useful when more than one derived
WebRequest type can process requests for the same protocol. The Microsoft Silverlight 3 and later runtime supports
multiple HTTP handlers each having different capabilities. For example, a web service that uses Representational State
Transfer (REST) might require the System.Net.Browser.WebRequestCreator.ClientHttp handler while a SOAP web
service might be able to use the default System.Net.Browser.WebRequestCreator.BrowserHttp handler.
WebRequest.Credentials WebRequest.Credentials
I n this Article
When overridden in a descendant class, gets or sets the network credentials used for authenticating the request with
the Internet resource.

public virtual System.Net.ICredentials Credentials { get; set; }


member this.Credentials : System.Net.ICredentials with get, set

Returns
ICredentials ICredentials
An ICredentials containing the authentication credentials associated with the request. The default is null .
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example sets the Credentials property using the default credentials of the current user. When the request
is made, credentials stored in this property are used to validate the client. This is identical to setting the
UseDefaultCredentials property to true .

// Create a request for the URL.


WebRequest request = WebRequest.Create ("http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

Remarks
The Credentials property contains the authentication credentials required to access the Internet resource.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.DefaultCachePolicy WebRequest.Default
CachePolicy
I n this Article
Gets or sets the default cache policy for this request.

public static System.Net.Cache.RequestCachePolicy DefaultCachePolicy { get; set; }


member this.DefaultCachePolicy : System.Net.Cache.RequestCachePolicy with get, set

Returns
RequestCachePolicy RequestCachePolicy
A HttpRequestCachePolicy that specifies the cache policy in effect for this request when no other policy is applicable.

Examples
The following code example demonstrates setting the default cache policy for Web requests.
public static WebResponse GetResponseFromServer2(Uri uri)
{
RequestCachePolicy policy =
new RequestCachePolicy( RequestCacheLevel.NoCacheNoStore);
WebRequest request = WebRequest.Create(uri);
WebRequest.DefaultCachePolicy = policy;
WebResponse response = request.GetResponse();
Console.WriteLine("Policy is {0}.", policy.ToString());
Console.WriteLine("Is the response from the cache? {0}", response.IsFromCache);
return response;
}

Remarks
This policy is used for this request if the following conditions exist:
There is no DefaultCachePolicy property specified for this request.
The machine and application configuration files do not specify a cache policy that is applicable to the Uniform Resource
Identifier (URI) used to create this request.
The cache policy determines whether the requested resource can be taken from a cache instead of sending the request
to the resource host computer.
A copy of a resource is only added to the cache if the response stream for the resource is retrieved and read to the end
of the stream. So another request for the same resource could use a cached copy, depending on the cache policy level
for this request.
See RequestCachePolicyRequestCachePolicy
Also CachePolicyCachePolicy
WebRequest.DefaultWebProxy WebRequest.DefaultWeb
Proxy
I n this Article
Gets or sets the global HTTP proxy.

public static System.Net.IWebProxy DefaultWebProxy { get; set; }


member this.DefaultWebProxy : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
An IWebProxy used by every call to instances of WebRequest.

Remarks
The DefaultWebProxy property gets or sets the global proxy. The DefaultWebProxy property determines the default
proxy that all WebRequest instances use if the request supports proxies and no proxy is set explicitly using the Proxy
property. Proxies are currently supported by FtpWebRequest and HttpWebRequest.
The DefaultWebProxy property reads proxy settings from the app.config file. If there is no config file, the current user's
Internet Explorer (IE ) proxy settings are used.
If the DefaultWebProxy property is set to null, all subsequent instances of the WebRequest class created by the Create
or CreateDefault methods do not have a proxy.
WebRequest.EndGetRequestStream WebRequest.EndGet
RequestStream
I n this Article
When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

public virtual System.IO.Stream EndGetRequestStream (IAsyncResult asyncResult);


abstract member EndGetRequestStream : IAsyncResult -> System.IO.Stream
override this.EndGetRequestStream : IAsyncResult -> System.IO.Stream

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult that references a pending request for a stream.
Returns
Stream Stream
A Stream to write data to.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example obtains and uses the request stream by calling the EndGetRequestStream. The
EndGetRequestStream method completes the asynchronous call to BeginGetRequestStream.
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the request state of the request.
public WebRequest request;
public RequestState()
{
request = null;
}
}

class WebRequest_BeginGetRequeststream
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
static void Main()
{
// Create a new request to the mentioned URL.
WebRequest myWebRequest= WebRequest.Create("http://www.contoso.com");

// Create an instance of the RequestState and assign


// 'myWebRequest' to it's request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myWebRequest;
myWebRequest.ContentType="application/x-www-form-urlencoded";
myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'Method' property to 'POST' to post data to a Uri.


myRequestState.request.Method="POST";
// Start the Asynchronous 'BeginGetRequestStream' method call.
IAsyncResult r=(IAsyncResult) myWebRequest.BeginGetRequestStream(
new AsyncCallback(ReadCallback),myRequestState);
// Pause the current thread until the async operation completes.
Console.WriteLine("main thread waiting...");
allDone.WaitOne();
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse = myWebRequest.GetResponse();
Console.WriteLine("The string has been posted.");
Console.WriteLine("Please wait for the response...");

Stream streamResponse = myWebResponse.GetResponseStream();


StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of the HTML page are ");

while (count > 0)


{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}

// Close the Stream Object.


streamResponse.Close();
streamRead.Close();

// Release the HttpWebResponse Resource.


myWebResponse.Close();
}
private static void ReadCallback(IAsyncResult asynchronousResult)
{
RequestState myRequestState =(RequestState) asynchronousResult.AsyncState;
WebRequest myWebRequest = myRequestState.request;

// End the Asynchronus request.


Stream streamResponse = myWebRequest.EndGetRequestStream(asynchronousResult);

// Create a string that is to be posted to the uri.


Console.WriteLine("Please enter a string to be posted:");
string postData = Console.ReadLine();
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Write the data to the stream.


streamResponse.Write(byteArray,0,postData.Length);
streamResponse.Close();
allDone.Set();
}
}

Remarks
The EndGetRequestStream method completes an asynchronous stream request that was started by the
BeginGetRequestStream method.
Note

To avoid timing issues with garbage collection, be sure to close the response stream by calling the Close method on the
stream returned by GetResponseStream after calling EndGetResponse.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See BeginGetRequestStream(AsyncCallback, Object)BeginGetRequestStream(AsyncCallback, Object)
Also Making Asynchronous Requests
WebRequest.EndGetResponse WebRequest.EndGet
Response
I n this Article
When overridden in a descendant class, returns a WebResponse.

public virtual System.Net.WebResponse EndGetResponse (IAsyncResult asyncResult);


abstract member EndGetResponse : IAsyncResult -> System.Net.WebResponse
override this.EndGetResponse : IAsyncResult -> System.Net.WebResponse

Parameters
asyncResult IAsyncResult IAsyncResult
An IAsyncResult that references a pending request for a response.
Returns
WebResponse WebResponse
A WebResponse that contains a response to the Internet request.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example calls the EndGetResponse to retrieve the target resource.

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the state of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder requestData;
public byte[] bufferRead;
public WebRequest request;
public WebResponse response;
public Stream responseStream;
public RequestState()
{
bufferRead = new byte[BUFFER_SIZE];
requestData = new StringBuilder("");
request = null;
responseStream = null;
}
}
class WebRequest_BeginGetResponse
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int BUFFER_SIZE = 1024;
static void Main()
{
try
{
// Create a new webrequest to the mentioned URL.
WebRequest myWebRequest= WebRequest.Create("http://www.contoso.com");

// Please, set the proxy to a correct value.


WebProxy proxy=new WebProxy("myproxy:80");

proxy.Credentials=new NetworkCredential("srikun","simrin123");
myWebRequest.Proxy=proxy;
// Create a new instance of the RequestState.
RequestState myRequestState = new RequestState();
// The 'WebRequest' object is associated to the 'RequestState' object.
myRequestState.request = myWebRequest;
// Start the Asynchronous call for response.
IAsyncResult asyncResult=(IAsyncResult) myWebRequest.BeginGetResponse(new
AsyncCallback(RespCallback),myRequestState);
allDone.WaitOne();
// Release the WebResponse resource.
myRequestState.response.Close();
Console.Read();
}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
private static void RespCallback(IAsyncResult asynchronousResult)
{
try
{
// Set the State of request to asynchronous.
RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
WebRequest myWebRequest1=myRequestState.request;
// End the Asynchronous response.
myRequestState.response = myWebRequest1.EndGetResponse(asynchronousResult);
// Read the response into a 'Stream' object.
Stream responseStream = myRequestState.response.GetResponseStream();
myRequestState.responseStream=responseStream;
// Begin the reading of the contents of the HTML page and print it to the console.
IAsyncResult asynchronousResultRead = responseStream.BeginRead(myRequestState.bufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);

}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : " + e.Source);
Console.WriteLine("Message : " + e.Message);
}
}
private static void ReadCallBack(IAsyncResult asyncResult)
{
try
{
// Result state is set to AsyncState.
RequestState myRequestState = (RequestState)asyncResult.AsyncState;
Stream responseStream = myRequestState.responseStream;
int read = responseStream.EndRead( asyncResult );
// Read the contents of the HTML page and then print to the console.
if (read > 0)
{
myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.bufferRead, 0,
read));
IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.bufferRead, 0,
BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
}
else
{
Console.WriteLine("
The HTML page Contents are: ");
if(myRequestState.requestData.Length>1)
{
string sringContent;
sringContent = myRequestState.requestData.ToString();
Console.WriteLine(sringContent);
}
Console.WriteLine("
Press 'Enter' key to continue........");
responseStream.Close();
allDone.Set();
}
}
catch(WebException e)
{
Console.WriteLine("WebException raised!");
Console.WriteLine("
{0}",e.Message);
Console.WriteLine("
{0}",e.Status);
}
catch(Exception e)
{
Console.WriteLine("Exception raised!");
Console.WriteLine("Source : {0}" , e.Source);
Console.WriteLine("Message : {0}" , e.Message);
}

Remarks
The EndGetResponse method completes an asynchronous request for an Internet resource that was started with the
BeginGetResponse method.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See BeginGetResponse(AsyncCallback, Object)BeginGetResponse(AsyncCallback, Object)
Also Making Asynchronous Requests
WebRequest.GetObjectData WebRequest.GetObjectData
I n this Article
Populates a SerializationInfo with the data needed to serialize the target object.
protected virtual void GetObjectData (System.Runtime.Serialization.SerializationInfo
serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
abstract member GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
WebRequest.GetRequestStream WebRequest.GetRequest
Stream
I n this Article
When overridden in a descendant class, returns a Stream for writing data to the Internet resource.

public virtual System.IO.Stream GetRequestStream ();


abstract member GetRequestStream : unit -> System.IO.Stream
override this.GetRequestStream : unit -> System.IO.Stream

Returns
Stream Stream
A Stream for writing data to the Internet resource.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example uses the GetRequestStream method to obtain a stream and then writes data that stream.

// Set the 'ContentType' property of the WebRequest.


myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'ContentLength' property of the WebRequest.


myWebRequest.ContentLength=byteArray.Length;
Stream newStream=myWebRequest.GetRequestStream();
newStream.Write(byteArray,0,byteArray.Length);

// Close the Stream object.


newStream.Close();

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.


WebResponse myWebResponse=myWebRequest.GetResponse();

Remarks
The GetRequestStream method initiates a request to send data to the Internet resource and returns a Stream instance
for sending data to the Internet resource.
The GetRequestStream method provides synchronous access to the Stream. For asynchronous access, use the
BeginGetRequestStream and EndGetRequestStream methods.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See BeginGetRequestStream(AsyncCallback, Object)BeginGetRequestStream(AsyncCallback, Object)
Also Using Streams on the Network
WebRequest.GetRequestStreamAsync WebRequest.Get
RequestStreamAsync
I n this Article
When overridden in a descendant class, returns a Stream for writing data to the Internet resource as an asynchronous
operation.
public virtual System.Threading.Tasks.Task<System.IO.Stream> GetRequestStreamAsync ();
abstract member GetRequestStreamAsync : unit -> System.Threading.Tasks.Task<System.IO.Stream>
override this.GetRequestStreamAsync : unit -> System.Threading.Tasks.Task<System.IO.Stream>

Returns
Task<Stream>
The task object representing the asynchronous operation.

Remarks
This operation will not block. The returned Task<TResult> object will complete when the Stream for writing data to the
Internet resource is available.
After you call GetRequestStreamAsync, make sure you close the request stream before you call GetResponseAsync.
WebRequest.GetResponse WebRequest.GetResponse
I n this Article
When overridden in a descendant class, returns a response to an Internet request.
public virtual System.Net.WebResponse GetResponse ();
abstract member GetResponse : unit -> System.Net.WebResponse
override this.GetResponse : unit -> System.Net.WebResponse

Returns
WebResponse WebResponse
A WebResponse containing the response to the Internet request.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example sets the Timeout property to 10000 milliseconds. If the timeout period expires before the
resource can be returned, a WebException is thrown.

// Create a new WebRequest Object to the mentioned URL.


WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");
Console.WriteLine("
The Timeout time of the request before setting is : {0} milliseconds",myWebRequest.Timeout);

// Set the 'Timeout' property in Milliseconds.


myWebRequest.Timeout=10000;

// This request will throw a WebException if it reaches the timeout limit before it is able to fetch
the resource.
WebResponse myWebResponse=myWebRequest.GetResponse();

Remarks
The GetResponse method sends a request to an Internet resource and returns a WebResponse instance. If the request
has already been initiated by a call to GetRequestStream, the GetResponse method completes the request and returns
any response.
The GetResponse method provides synchronous access to the WebResponse. For asynchronous access, use the
BeginGetResponse and EndGetResponse methods.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
Note

If a WebException is thrown, use the Response and Status properties of the exception to determine the response from
the server.
See BeginGetResponse(AsyncCallback, Object)BeginGetResponse(AsyncCallback, Object)
Also WebResponseWebResponse
WebRequest.GetResponseAsync WebRequest.Get
ResponseAsync
I n this Article
When overridden in a descendant class, returns a response to an Internet request as an asynchronous operation.

public virtual System.Threading.Tasks.Task<System.Net.WebResponse> GetResponseAsync ();


abstract member GetResponseAsync : unit -> System.Threading.Tasks.Task<System.Net.WebResponse>
override this.GetResponseAsync : unit -> System.Threading.Tasks.Task<System.Net.WebResponse>

Returns
Task<WebResponse>
The task object representing the asynchronous operation.

Remarks
This operation will not block. The returned Task<TResult> object will complete after a response to an Internet request
is available.
WebRequest.GetSystemWebProxy WebRequest.Get
SystemWebProxy
I n this Article
Returns a proxy configured with the Internet Explorer settings of the currently impersonated user.

public static System.Net.IWebProxy GetSystemWebProxy ();


static member GetSystemWebProxy : unit -> System.Net.IWebProxy

Returns
IWebProxy IWebProxy
An IWebProxy used by every call to instances of WebRequest.

Remarks
GetSystemWebProxy method reads the current user's Internet Explorer (IE ) proxy settings. This process includes the IE
options to automatically detect proxy settings, use an automatic configuration script, manual proxy server settings, and
advanced manual proxy server settings.
If your application is impersonating several users, you can use the GetSystemWebProxy method to retrieve a proxy for
each impersonated user.
WebRequest.Headers WebRequest.Headers
I n this Article
When overridden in a descendant class, gets or sets the collection of header name/value pairs associated with the
request.

public virtual System.Net.WebHeaderCollection Headers { get; set; }


member this.Headers : System.Net.WebHeaderCollection with get, set

Returns
WebHeaderCollection WebHeaderCollection
A WebHeaderCollection containing the header name/value pairs associated with this request.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example displays the header name/value pairs associated with this request.

// Create a new request to the mentioned URL.


WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.


WebResponse myWebResponse=myWebRequest.GetResponse();

// Release the resources of response object.


myWebResponse.Close();
Console.WriteLine("
The HttpHeaders are
{0}",myWebRequest.Headers);

Remarks
The Headers property contains a WebHeaderCollection instance containing the header information to send to the
Internet resource.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See WebHeaderCollectionWebHeaderCollection
Also
WebRequest.ImpersonationLevel WebRequest.
ImpersonationLevel
I n this Article
Gets or sets the impersonation level for the current request.

public System.Security.Principal.TokenImpersonationLevel ImpersonationLevel { get; set; }


member this.ImpersonationLevel : System.Security.Principal.TokenImpersonationLevel with get, set

Returns
TokenImpersonationLevel TokenImpersonationLevel
A TokenImpersonationLevel value.

Remarks
The impersonation level determines how the server can use the client's credentials.
WebRequest.ISerializable.GetObjectData
I n this Article
When overridden in a descendant class, populates a SerializationInfo instance with the data needed to serialize the
WebRequest.

void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,


System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
A SerializationInfo, which holds the serialized data for the WebRequest.
streamingContext StreamingContext
A StreamingContext that contains the destination of the serialized stream associated with the new WebRequest.
Exceptions
NotImplementedException
An attempt is made to serialize the object, when the interface is not overridden in a descendant class.
WebRequest.Method WebRequest.Method
I n this Article
When overridden in a descendant class, gets or sets the protocol method to use in this request.
public virtual string Method { get; set; }
member this.Method : string with get, set

Returns
String String
The protocol method to use in this request.
Exceptions
NotImplementedException NotImplementedException
If the property is not overridden in a descendant class, any attempt is made to get or set the property.

Examples
The following example sets the Method property to POST to indicate that the request will post data to the target host.
using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;

public class RequestState


{
// This class stores the request state of the request.
public WebRequest request;
public RequestState()
{
request = null;
}
}

class WebRequest_BeginGetRequeststream
{
public static ManualResetEvent allDone= new ManualResetEvent(false);
static void Main()
{
// Create a new request to the mentioned URL.
WebRequest myWebRequest= WebRequest.Create("http://www.contoso.com");

// Create an instance of the RequestState and assign


// 'myWebRequest' to it's request field.
RequestState myRequestState = new RequestState();
myRequestState.request = myWebRequest;
myWebRequest.ContentType="application/x-www-form-urlencoded";

// Set the 'Method' property to 'POST' to post data to a Uri.


myRequestState.request.Method="POST";
// Start the Asynchronous 'BeginGetRequestStream' method call.
IAsyncResult r=(IAsyncResult) myWebRequest.BeginGetRequestStream(
new AsyncCallback(ReadCallback),myRequestState);
// Pause the current thread until the async operation completes.
Console.WriteLine("main thread waiting...");
allDone.WaitOne();
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse = myWebRequest.GetResponse();
Console.WriteLine("The string has been posted.");
Console.WriteLine("Please wait for the response...");

Stream streamResponse = myWebResponse.GetResponseStream();


StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of the HTML page are ");

while (count > 0)


{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}

// Close the Stream Object.


streamResponse.Close();
streamRead.Close();

// Release the HttpWebResponse Resource.


myWebResponse.Close();
}
private static void ReadCallback(IAsyncResult asynchronousResult)
{
RequestState myRequestState =(RequestState) asynchronousResult.AsyncState;
WebRequest myWebRequest = myRequestState.request;

// End the Asynchronus request.


Stream streamResponse = myWebRequest.EndGetRequestStream(asynchronousResult);

// Create a string that is to be posted to the uri.


Console.WriteLine("Please enter a string to be posted:");
string postData = Console.ReadLine();
// Convert the string into a byte array.
byte[] byteArray = Encoding.UTF8.GetBytes(postData);

// Write the data to the stream.


streamResponse.Write(byteArray,0,postData.Length);
streamResponse.Close();
allDone.Set();
}
}

Remarks
When overridden in a descendant class, the Method property contains the request method to use in this request.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.PreAuthenticate WebRequest.Pre
Authenticate
I n this Article
When overridden in a descendant class, indicates whether to pre-authenticate the request.

public virtual bool PreAuthenticate { get; set; }


member this.PreAuthenticate : bool with get, set

Returns
Boolean Boolean
true to pre-authenticate; otherwise, false .

Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example sets the PreAuthenticate property to true so that the NetworkCredential stored in the
Credentials property will be sent to along with the resource request.

// Create a new webrequest to the mentioned URL.


WebRequest myWebRequest=WebRequest.Create(url);

// Set 'Preauthenticate' property to true. Credentials will be sent with the request.
myWebRequest.PreAuthenticate=true;

Console.WriteLine("
Please enter your credentials for the requested Url");
Console.WriteLine("UserName");
string UserName=Console.ReadLine();
Console.WriteLine("Password");
string Password=Console.ReadLine();

// Create a New 'NetworkCredential' object.


NetworkCredential networkCredential=new NetworkCredential(UserName,Password);

// Associate the 'NetworkCredential' object with the 'WebRequest' object.


myWebRequest.Credentials=networkCredential;

// Assign the response object of 'WebRequest' to a 'WebResponse' variable.


WebResponse myWebResponse=myWebRequest.GetResponse();

Remarks
With the exception of the first request, the PreAuthenticate property indicates whether to send authentication
information with subsequent requests without waiting to be challenged by the server. When PreAuthenticate is false ,
the WebRequest waits for an authentication challenge before sending authentication information.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.Proxy WebRequest.Proxy
I n this Article
When overridden in a descendant class, gets or sets the network proxy to use to access this Internet resource.
public virtual System.Net.IWebProxy Proxy { get; set; }
member this.Proxy : System.Net.IWebProxy with get, set

Returns
IWebProxy IWebProxy
The IWebProxy to use to access the Internet resource.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example displays the current network proxy address and allows the user to assign a new network proxy
address and port number.
// Create a new request to the mentioned URL.
WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");

WebProxy myProxy=new WebProxy();


// Obtain the Proxy Prperty of the Default browser.
myProxy=(WebProxy)myWebRequest.Proxy;

// Print myProxy address to the console.


Console.WriteLine("
The actual default Proxy settings are {0}",myProxy.Address);
try
{
Console.WriteLine("
Please enter the new Proxy Address to be set ");
Console.WriteLine("The format of the address should be http://proxyUriAddress:portaddress");
Console.WriteLine("Example:http://proxyadress.com:8080");
string proxyAddress;
proxyAddress =Console.ReadLine();

if(proxyAddress.Length==0)
{
myWebRequest.Proxy=myProxy;
}
else
{
Console.WriteLine("
Please enter the Credentials");
Console.WriteLine("Username:");
string username;
username =Console.ReadLine();
Console.WriteLine("
Password:");
string password;
password =Console.ReadLine();

// Create a new Uri object.


Uri newUri=new Uri(proxyAddress);
// Associate the new Uri object to the myProxy object.
myProxy.Address=newUri;

// Create a NetworkCredential object and is assign to the Credentials property of the Proxy
object.
myProxy.Credentials=new NetworkCredential(username,password);
myWebRequest.Proxy=myProxy;
}
Console.WriteLine("
The Address of the new Proxy settings are {0}",myProxy.Address);
WebResponse myWebResponse=myWebRequest.GetResponse();

// Print the HTML contents of the page to the console.


Stream streamResponse=myWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader( streamResponse );
Char[] readBuff = new Char[256];
int count = streamRead.Read( readBuff, 0, 256 );
Console.WriteLine("
The contents of the Html pages are :");
while (count > 0)
{
String outputData = new String(readBuff, 0, count);
Console.Write(outputData);
count = streamRead.Read(readBuff, 0, 256);
}

// Close the Stream object.


streamResponse.Close();
streamRead.Close();

// Release the HttpWebResponse Resource.


myWebResponse.Close();
Console.WriteLine("
Press any key to continue.........");
Console.Read();
}
catch(UriFormatException e)
{
Console.WriteLine("
UriFormatException is thrown.Message is {0}",e.Message);
Console.WriteLine("
The format of the myProxy address you entered is invalid");
Console.WriteLine("
Press any key to continue.........");
Console.Read();
}

Remarks
The Proxy property identifies the network proxy that the request uses to access the Internet resource. The request is
made through the proxy server rather than directly to the Internet resource.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
See IWebProxyIWebProxy
Also
WebRequest.RegisterPortableWebRequestCreator Web
Request.RegisterPortableWebRequestCreator
I n this Article
Register an IWebRequestCreate object.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public static void RegisterPortableWebRequestCreator (System.Net.IWebRequestCreate creator);
static member RegisterPortableWebRequestCreator : System.Net.IWebRequestCreate -> unit

Parameters
creator IWebRequestCreate IWebRequestCreate
The IWebRequestCreate object to register.
Attributes ObsoleteAttribute
WebRequest.RegisterPrefix WebRequest.RegisterPrefix
I n this Article
Registers a WebRequest descendant for the specified URI.
public static bool RegisterPrefix (string prefix, System.Net.IWebRequestCreate creator);
static member RegisterPrefix : string * System.Net.IWebRequestCreate -> bool

Parameters
prefix String String
The complete URI or URI prefix that the WebRequest descendant services.
creator IWebRequestCreate IWebRequestCreate
The create method that the WebRequest calls to create the WebRequest descendant.
Returns
Boolean Boolean
true if registration is successful; otherwise, false .
Exceptions
ArgumentNullException ArgumentNullException
prefix is null
-or-
creator is null .

Remarks
The RegisterPrefix method registers WebRequest descendants to service requests. WebRequest descendants are
typically registered to handle a specific protocol, such HTTP or FTP, but can be registered to handle a request to a
specific server or path on a server.
The pre-registered reserve types already registered include the following:
http://

https://

ftp://

file://

For more information, see the Create(String) and Create(Uri) methods.


Duplicate prefixes are not allowed. RegisterPrefix returns false if an attempt is made to register a duplicate prefix.
Note

The HttpWebRequest class is registered to service requests for HTTP and HTTPS schemes by default. Attempts to
register a different WebRequest descendant for these schemes will fail.
WebRequest.RequestUri WebRequest.RequestUri
I n this Article
When overridden in a descendant class, gets the URI of the Internet resource associated with the request.
public virtual Uri RequestUri { get; }
member this.RequestUri : Uri

Returns
Uri Uri
A Uri representing the resource associated with the request
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example checks the RequestUri property to determine the site originally requested.
// Create a new WebRequest Object to the mentioned URL.
WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");
Console.WriteLine("
The Uri that was requested is {0}",myWebRequest.RequestUri);
// Assign the response object of 'WebRequest' to a 'WebResponse' variable.
WebResponse myWebResponse=myWebRequest.GetResponse();
// Get the stream containing content returned by the server.
Stream streamResponse=myWebResponse.GetResponseStream();
Console.WriteLine("
The Uri that responded to the WebRequest is '{0}'",myWebResponse.ResponseUri);
StreamReader reader = new StreamReader (streamResponse);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine("
The HTML Contents received:");
Console.WriteLine (responseFromServer);
// Cleanup the streams and the response.
reader.Close ();
streamResponse.Close ();
myWebResponse.Close ();

Remarks
When overridden in a descendant class, the RequestUri property contains the Uri instance that Create method uses to
create the request.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.Timeout WebRequest.Timeout
I n this Article
Gets or sets the length of time, in milliseconds, before the request times out.
public virtual int Timeout { get; set; }
member this.Timeout : int with get, set

Returns
Int32 Int32
The length of time, in milliseconds, until the request times out, or the value Infinite to indicate that the request does not
time out. The default value is defined by the descendant class.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example sets the Timeout property to 10000 milliseconds. If the timeout period expires before the
resource can be returned, a WebException is thrown.

// Create a new WebRequest Object to the mentioned URL.


WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");
Console.WriteLine("
The Timeout time of the request before setting is : {0} milliseconds",myWebRequest.Timeout);

// Set the 'Timeout' property in Milliseconds.


myWebRequest.Timeout=10000;

// This request will throw a WebException if it reaches the timeout limit before it is able to fetch
the resource.
WebResponse myWebResponse=myWebRequest.GetResponse();

Remarks
The Timeout property indicates the length of time, in milliseconds, until the request times out and throws a
WebException. The Timeout property affects only synchronous requests made with the GetResponse method. To time
out asynchronous requests, use the Abort method.
Note

The WebRequest class is an abstract class. The actual behavior of WebRequest instances at run time is determined by
the descendant class returned by the WebRequest.Create method. For more information about default values and
exceptions, see the documentation for the descendant classes, such as HttpWebRequest and FileWebRequest.
WebRequest.UseDefaultCredentials WebRequest.Use
DefaultCredentials
I n this Article
When overridden in a descendant class, gets or sets a Boolean value that controls whether DefaultCredentials are sent
with requests.
public virtual bool UseDefaultCredentials { get; set; }
member this.UseDefaultCredentials : bool with get, set

Returns
Boolean Boolean
true if the default credentials are used; otherwise false . The default value is false .

Exceptions
InvalidOperationException InvalidOperationException
You attempted to set this property after the request was sent.
NotImplementedException NotImplementedException
Any attempt is made to access the property, when the property is not overridden in a descendant class.

Remarks
Set this property to true when requests made by this WebRequest object should, if requested by the server, be
authenticated using the credentials of the currently logged on user. For client applications, this is the desired behavior
in most scenarios. For middle tier applications, such as ASP.NET applications, instead of using this property, you would
typically set the Credentials property to the credentials of the client on whose behalf the request is made.
WebRequest WebRequest
I n this Article

Overloads
WebRequest()
Initializes a new instance of the WebRequest class.

WebRequest(SerializationInfo, StreamingContext) WebRequest(


SerializationInfo, StreamingContext) Initializes a new instance of the WebRequest class from the
specified instances of the SerializationInfo and
StreamingContext classes.

WebRequest()
Initializes a new instance of the WebRequest class.
protected WebRequest ();

Examples
The following example shows how to create a WebRequest instance by calling the Create method on the WebRequest
class.
WebRequest myRequest = WebRequest.Create("http://www.contoso.com");

Remarks
Use the Create method to initialize new WebRequest instances. Do not use the constructor.

WebRequest(SerializationInfo, StreamingContext)
WebRequest(SerializationInfo, StreamingContext)
Initializes a new instance of the WebRequest class from the specified instances of the SerializationInfo and
StreamingContext classes.
protected WebRequest (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.WebRequest : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.WebRequest

Parameters
serializationInfo SerializationInfo SerializationInfo
A SerializationInfo that contains the information required to serialize the new WebRequest instance.
streamingContext StreamingContext StreamingContext
A StreamingContext that indicates the source of the serialized stream associated with the new WebRequest instance.
Exceptions
NotImplementedException NotImplementedException
Any attempt is made to access the constructor, when the constructor is not overridden in a descendant class.
Remarks
When implemented by a descendant class, this constructor implements the ISerializable interface for the WebRequest
descendant.
Notice that an application must run in full trust mode when using serialization.
See XML and SOAP Serialization
Also
WebRequestMethods WebRequestMethods Class
Container class for WebRequestMethods.Ftp, WebRequestMethods.File, and WebRequestMethods.Http classes. This
class cannot be inherited

D eclaration
public static class WebRequestMethods
type WebRequestMethods = class

I nheritance H ierarchy
Object Object
WebRequestMethods.File WebRequestMethods.File Class
Represents the types of file protocol methods that can be used with a FILE request. This class cannot be inherited.

D eclaration
public static class WebRequestMethods.File
type WebRequestMethods.File = class

I nheritance H ierarchy
Object Object

Remarks
The members of this class can be used to set the Method property that determines the protocol method that is to be
used to perform a requested action, such as copying and retrieving a file.

Fields
DownloadFile
DownloadFile

Represents the FILE GET protocol method that is used to retrieve a file from a specified location.

UploadFile
UploadFile

Represents the FILE PUT protocol method that is used to copy a file to a specified location.
WebRequestMethods.File.DownloadFile WebRequest
Methods.File.DownloadFile
I n this Article
Represents the FILE GET protocol method that is used to retrieve a file from a specified location.

public const string DownloadFile;


val mutable DownloadFile : string

Returns
String String
WebRequestMethods.File.UploadFile WebRequest
Methods.File.UploadFile
I n this Article
Represents the FILE PUT protocol method that is used to copy a file to a specified location.

public const string UploadFile;


val mutable UploadFile : string

Returns
String String
WebRequestMethods.Ftp WebRequestMethods.Ftp Class
Represents the types of FTP protocol methods that can be used with an FTP request. This class cannot be inherited.

D eclaration
public static class WebRequestMethods.Ftp
type WebRequestMethods.Ftp = class

I nheritance H ierarchy
Object Object

Remarks
The members of this class can be used to set the Method property that determines the protocol method that is to be
used to perform a requested action, such as uploading or downloading a file.

Fields
AppendFile
AppendFile

Represents the FTP APPE protocol method that is used to append a file to an existing file on an FTP server.

DeleteFile
DeleteFile

Represents the FTP DELE protocol method that is used to delete a file on an FTP server.

DownloadFile
DownloadFile

Represents the FTP RETR protocol method that is used to download a file from an FTP server.

GetDateTimestamp
GetDateTimestamp

Represents the FTP MDTM protocol method that is used to retrieve the date-time stamp from a file on an FTP
server.

GetFileSize
GetFileSize

Represents the FTP SIZE protocol method that is used to retrieve the size of a file on an FTP server.

ListDirectory
ListDirectory
Represents the FTP NLIST protocol method that gets a short listing of the files on an FTP server.

ListDirectoryDetails
ListDirectoryDetails

Represents the FTP LIST protocol method that gets a detailed listing of the files on an FTP server.

MakeDirectory
MakeDirectory

Represents the FTP MKD protocol method creates a directory on an FTP server.

PrintWorkingDirectory
PrintWorkingDirectory

Represents the FTP PWD protocol method that prints the name of the current working directory.

RemoveDirectory
RemoveDirectory

Represents the FTP RMD protocol method that removes a directory.

Rename
Rename

Represents the FTP RENAME protocol method that renames a directory.

UploadFile
UploadFile

Represents the FTP STOR protocol method that uploads a file to an FTP server.

UploadFileWithUniqueName
UploadFileWithUniqueName

Represents the FTP STOU protocol that uploads a file with a unique name to an FTP server.
WebRequestMethods.Ftp.AppendFile WebRequest
Methods.Ftp.AppendFile
I n this Article
Represents the FTP APPE protocol method that is used to append a file to an existing file on an FTP server.

public const string AppendFile;


val mutable AppendFile : string

Returns
String String
WebRequestMethods.Ftp.DeleteFile WebRequest
Methods.Ftp.DeleteFile
I n this Article
Represents the FTP DELE protocol method that is used to delete a file on an FTP server.

public const string DeleteFile;


val mutable DeleteFile : string

Returns
String String
WebRequestMethods.Ftp.DownloadFile WebRequest
Methods.Ftp.DownloadFile
I n this Article
Represents the FTP RETR protocol method that is used to download a file from an FTP server.

public const string DownloadFile;


val mutable DownloadFile : string

Returns
String String
WebRequestMethods.Ftp.GetDateTimestamp Web
RequestMethods.Ftp.GetDateTimestamp
I n this Article
Represents the FTP MDTM protocol method that is used to retrieve the date-time stamp from a file on an FTP server.

public const string GetDateTimestamp;


val mutable GetDateTimestamp : string

Returns
String String
WebRequestMethods.Ftp.GetFileSize WebRequest
Methods.Ftp.GetFileSize
I n this Article
Represents the FTP SIZE protocol method that is used to retrieve the size of a file on an FTP server.

public const string GetFileSize;


val mutable GetFileSize : string

Returns
String String
WebRequestMethods.Ftp.ListDirectory WebRequest
Methods.Ftp.ListDirectory
I n this Article
Represents the FTP NLIST protocol method that gets a short listing of the files on an FTP server.

public const string ListDirectory;


val mutable ListDirectory : string

Returns
String String
WebRequestMethods.Ftp.ListDirectoryDetails Web
RequestMethods.Ftp.ListDirectoryDetails
I n this Article
Represents the FTP LIST protocol method that gets a detailed listing of the files on an FTP server.

public const string ListDirectoryDetails;


val mutable ListDirectoryDetails : string

Returns
String String
WebRequestMethods.Ftp.MakeDirectory WebRequest
Methods.Ftp.MakeDirectory
I n this Article
Represents the FTP MKD protocol method creates a directory on an FTP server.

public const string MakeDirectory;


val mutable MakeDirectory : string

Returns
String String
WebRequestMethods.Ftp.PrintWorkingDirectory Web
RequestMethods.Ftp.PrintWorkingDirectory
I n this Article
Represents the FTP PWD protocol method that prints the name of the current working directory.

public const string PrintWorkingDirectory;


val mutable PrintWorkingDirectory : string

Returns
String String
WebRequestMethods.Ftp.RemoveDirectory WebRequest
Methods.Ftp.RemoveDirectory
I n this Article
Represents the FTP RMD protocol method that removes a directory.

public const string RemoveDirectory;


val mutable RemoveDirectory : string

Returns
String String
WebRequestMethods.Ftp.Rename WebRequestMethods.
Ftp.Rename
I n this Article
Represents the FTP RENAME protocol method that renames a directory.

public const string Rename;


val mutable Rename : string

Returns
String String
WebRequestMethods.Ftp.UploadFile WebRequest
Methods.Ftp.UploadFile
I n this Article
Represents the FTP STOR protocol method that uploads a file to an FTP server.

public const string UploadFile;


val mutable UploadFile : string

Returns
String String
WebRequestMethods.Ftp.UploadFileWithUniqueName
WebRequestMethods.Ftp.UploadFileWithUniqueName
I n this Article
Represents the FTP STOU protocol that uploads a file with a unique name to an FTP server.

public const string UploadFileWithUniqueName;


val mutable UploadFileWithUniqueName : string

Returns
String String
WebRequestMethods.Http WebRequestMethods.Http
Class
Represents the types of HTTP protocol methods that can be used with an HTTP request.

D eclaration
public static class WebRequestMethods.Http
type WebRequestMethods.Http = class

I nheritance H ierarchy
Object Object

Fields
Connect
Connect

Represents the HTTP CONNECT protocol method that is used with a proxy that can dynamically switch to
tunneling, as in the case of SSL tunneling.

Get
Get

Represents an HTTP GET protocol method.

Head
Head

Represents an HTTP HEAD protocol method. The HEAD method is identical to GET except that the server only
returns message-headers in the response, without a message-body.

MkCol
MkCol

Represents an HTTP MKCOL request that creates a new collection (such as a collection of pages) at the location
specified by the request-Uniform Resource Identifier (URI).

Post
Post

Represents an HTTP POST protocol method that is used to post a new entity as an addition to a URI.

Put
Put

Represents an HTTP PUT protocol method that is used to replace an entity identified by a URI.
WebRequestMethods.Http.Connect WebRequest
Methods.Http.Connect
I n this Article
Represents the HTTP CONNECT protocol method that is used with a proxy that can dynamically switch to tunneling,
as in the case of SSL tunneling.
public const string Connect;
val mutable Connect : string

Returns
String String
WebRequestMethods.Http.Get WebRequestMethods.
Http.Get
I n this Article
Represents an HTTP GET protocol method.

public const string Get;


val mutable Get : string

Returns
String String

Remarks
The GET method retrieves the information or entity that is identified by the URI of the request. If that URI refers to a
script or other data-producing process, it is the data produced, not the text of the script, which is returned in the
response.
WebRequestMethods.Http.Head WebRequestMethods.
Http.Head
I n this Article
Represents an HTTP HEAD protocol method. The HEAD method is identical to GET except that the server only returns
message-headers in the response, without a message-body.
public const string Head;
val mutable Head : string

Returns
String String
WebRequestMethods.Http.MkCol WebRequestMethods.
Http.MkCol
I n this Article
Represents an HTTP MKCOL request that creates a new collection (such as a collection of pages) at the location
specified by the request-Uniform Resource Identifier (URI).
public const string MkCol;
val mutable MkCol : string

Returns
String String
WebRequestMethods.Http.Post WebRequestMethods.
Http.Post
I n this Article
Represents an HTTP POST protocol method that is used to post a new entity as an addition to a URI.

public const string Post;


val mutable Post : string

Returns
String String
WebRequestMethods.Http.Put WebRequestMethods.
Http.Put
I n this Article
Represents an HTTP PUT protocol method that is used to replace an entity identified by a URI.

public const string Put;


val mutable Put : string

Returns
String String
WebResponse WebResponse Class
Provides a response from a Uniform Resource Identifier (URI). This is an abstract class.

D eclaration
[System.Serializable]
public abstract class WebResponse : MarshalByRefObject, IDisposable,
System.Runtime.Serialization.ISerializable
type WebResponse = class
inherit MarshalByRefObject
interface ISerializable
interface IDisposable

I nheritance H ierarchy
Object Object
MarshalByRefObject MarshalByRefObject

Remarks
The WebResponse class is the abstract base class from which protocol-specific response classes are derived.
Applications can participate in request and response transactions in a protocol-agnostic manner using instances of the
WebResponse class while protocol-specific classes derived from WebResponse carry out the details of the request.
Client applications do not create WebResponse objects directly; they are created by calling the GetResponse method on
a WebRequest instance.

Constructors
WebResponse()
WebResponse()

Initializes a new instance of the WebResponse class.

WebResponse(SerializationInfo, StreamingContext)
WebResponse(SerializationInfo, StreamingContext)

Initializes a new instance of the WebResponse class from the specified instances of the SerializationInfo and
StreamingContext classes.

Properties
ContentLength
ContentLength

When overridden in a descendant class, gets or sets the content length of data being received.

ContentType
ContentType

When overridden in a derived class, gets or sets the content type of the data being received.
Headers
Headers

When overridden in a derived class, gets a collection of header name-value pairs associated with this request.

IsFromCache
IsFromCache

Gets a Boolean value that indicates whether this response was obtained from the cache.

IsMutuallyAuthenticated
IsMutuallyAuthenticated

Gets a Boolean value that indicates whether mutual authentication occurred.

ResponseUri
ResponseUri

When overridden in a derived class, gets the URI of the Internet resource that actually responded to the request.

SupportsHeaders
SupportsHeaders

Gets a value that indicates if headers are supported.

Methods
Close()
Close()

When overridden by a descendant class, closes the response stream.

Dispose()
Dispose()

Releases the unmanaged resources used by the WebResponse object.

Dispose(Boolean)
Dispose(Boolean)

Releases the unmanaged resources used by the WebResponse object, and optionally disposes of the managed
resources.

GetObjectData(SerializationInfo, StreamingContext)
GetObjectData(SerializationInfo, StreamingContext)
Populates a SerializationInfo with the data that is needed to serialize the target object.

GetResponseStream()
GetResponseStream()

When overridden in a descendant class, returns the data stream from the Internet resource.

IDisposable.Dispose()
IDisposable.Dispose()

When overridden in a derived class, releases all resources used by the WebResponse.

ISerializable.GetObjectData(SerializationInfo, StreamingContext)
ISerializable.GetObjectData(SerializationInfo, StreamingContext)

Populates a SerializationInfo instance with the data that is needed to serialize WebResponse.
WebResponse.Close WebResponse.Close
I n this Article
When overridden by a descendant class, closes the response stream.
public virtual void Close ();
abstract member Close : unit -> unit
override this.Close : unit -> unit

Exceptions
NotSupportedException NotSupportedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example uses the Close method to close the WebResponse .

// Create a 'WebRequest' object with the specified url.


WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");
// Send the 'WebRequest' and wait for response.
WebResponse myWebResponse = myWebRequest.GetResponse();

// Process the response here.


Console.WriteLine("
Response Received.Trying to Close the response stream..");
// Release resources of response object.
myWebResponse.Close();
Console.WriteLine("
Response Stream successfully closed");

Remarks
The Close method cleans up the resources used by a WebResponse and closes the underlying stream by calling the
Stream.Close method.
Note

The response must be closed to avoid running out of system resources. The response stream can be closed by calling
Stream.Close or Close.
Note

The WebResponse class is an abstract class. The actual behavior of WebResponse instances at run time is determined
by the descendant class returned by WebRequest.GetResponse. For more information about default values and
exceptions, please see the documentation for the descendant classes, such as HttpWebResponse and FileWebResponse.
See Using Streams on the Network
Also
WebResponse.ContentLength WebResponse.Content
Length
I n this Article
When overridden in a descendant class, gets or sets the content length of data being received.

public virtual long ContentLength { get; set; }


member this.ContentLength : int64 with get, set

Returns
Int64 Int64
The number of bytes returned from the Internet resource.
Exceptions
NotSupportedException NotSupportedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example uses the ContentLength property to obtain the Length of the resource returned.

// Create a 'WebRequest' with the specified url.


WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");

// Send the 'WebRequest' and wait for response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Display the content length and content type received as headers in the response object.
Console.WriteLine("
Content length :{0}, Content Type : {1}",
myWebResponse.ContentLength,
myWebResponse.ContentType);

// Release resources of response object.


myWebResponse.Close();

Remarks
The ContentLength property contains the length, in bytes, of the response from the Internet resource. For request
methods that contain header information, the ContentLength does not include the length of the header information.
Note

The WebResponse class is an abstract class. The actual behavior of WebResponse instances at run time is determined
by the descendant class returned by WebRequest.GetResponse. For more information about default values and
exceptions, please see the documentation for the descendant classes, such as HttpWebResponse and FileWebResponse.
WebResponse.ContentType WebResponse.ContentType
I n this Article
When overridden in a derived class, gets or sets the content type of the data being received.
public virtual string ContentType { get; set; }
member this.ContentType : string with get, set

Returns
String String
A string that contains the content type of the response.
Exceptions
NotSupportedException NotSupportedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example uses the ContentType property to obtain the content type of the response.

// Create a 'WebRequest' with the specified url.


WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");

// Send the 'WebRequest' and wait for response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Display the content length and content type received as headers in the response object.
Console.WriteLine("
Content length :{0}, Content Type : {1}",
myWebResponse.ContentLength,
myWebResponse.ContentType);

// Release resources of response object.


myWebResponse.Close();

Remarks
The ContentType property contains the MIME content type of the response from the Internet resource, if known.
Note

The WebResponse class is an abstract class. The actual behavior of WebResponse instances at run time is determined
by the descendant class returned by WebRequest.GetResponse. For more information about default values and
exceptions, please see the documentation for the descendant classes, such as HttpWebResponse and FileWebResponse.
WebResponse.Dispose WebResponse.Dispose
I n this Article

Overloads
Dispose() Dispose()
Releases the unmanaged resources used by the WebResponse
object.

Dispose(Boolean) Dispose(Boolean)
Releases the unmanaged resources used by the WebResponse
object, and optionally disposes of the managed resources.

Dispose() Dispose()
Releases the unmanaged resources used by the WebResponse object.
public void Dispose ();
abstract member Dispose : unit -> unit
override this.Dispose : unit -> unit

Dispose(Boolean) Dispose(Boolean)
Releases the unmanaged resources used by the WebResponse object, and optionally disposes of the managed
resources.
protected virtual void Dispose (bool disposing);
abstract member Dispose : bool -> unit
override this.Dispose : bool -> unit

Parameters
disposing Boolean Boolean
true to release both managed and unmanaged resources; false to releases only unmanaged resources.
Remarks
This method is called by the public Dispose() method and the Finalize method. Dispose() invokes the protected
Dispose(Boolean) method with the disposing parameter set to true . Finalize invokes Dispose with disposing set
to false .
When the disposing parameter is true , this method releases all resources held by any managed objects that this
WebResponse references. This method invokes the Dispose() method of each referenced object.
Note

This member outputs trace information when you enable network tracing in your application. For more information,
see Network Tracing in the .NET Framework.
WebResponse.GetObjectData WebResponse.GetObject
Data
I n this Article
Populates a SerializationInfo with the data that is needed to serialize the target object.

protected virtual void GetObjectData (System.Runtime.Serialization.SerializationInfo


serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext);
abstract member GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit
override this.GetObjectData : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> unit

Parameters
serializationInfo SerializationInfo SerializationInfo
The SerializationInfo to populate with data.
streamingContext StreamingContext StreamingContext
A StreamingContext that specifies the destination for this serialization.

Remarks
Any objects included in the SerializationInfo are automatically tracked and serialized by the formatter.
WebResponse.GetResponseStream WebResponse.Get
ResponseStream
I n this Article
When overridden in a descendant class, returns the data stream from the Internet resource.

public virtual System.IO.Stream GetResponseStream ();


abstract member GetResponseStream : unit -> System.IO.Stream
override this.GetResponseStream : unit -> System.IO.Stream

Returns
Stream Stream
An instance of the Stream class for reading data from the Internet resource.
Exceptions
NotSupportedException NotSupportedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.

Examples
The following example uses GetResponseStream to return a StreamReader instance. A small local buffer is used to
read data from the StreamReader and output it to the console.
// Create a 'WebRequest' object with the specified url.
WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");

// Send the 'WebRequest' and wait for response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Obtain a 'Stream' object associated with the response object.


Stream ReceiveStream = myWebResponse.GetResponseStream();

Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

// Pipe the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( ReceiveStream, encode );
Console.WriteLine("
Response stream received");
Char[] read = new Char[256];

// Read 256 charcters at a time.


int count = readStream.Read( read, 0, 256 );
Console.WriteLine("HTML...\r
");

while (count > 0)


{
// Dump the 256 characters on a string and display the string onto the console.
String str = new String(read, 0, count);
Console.Write(str);
count = readStream.Read(read, 0, 256);
}

Console.WriteLine("");
// Release the resources of stream object.
readStream.Close();

// Release the resources of response object.


myWebResponse.Close();

Remarks
The GetResponseStream method returns the data stream from the Internet resource.
Note

The response stream must be closed to avoid running out of system resources. The response stream can be closed by
calling Stream.Close or Close
See Using Streams on the Network
Also
WebResponse.Headers WebResponse.Headers
I n this Article
When overridden in a derived class, gets a collection of header name-value pairs associated with this request.
public virtual System.Net.WebHeaderCollection Headers { get; }
member this.Headers : System.Net.WebHeaderCollection

Returns
WebHeaderCollection WebHeaderCollection
An instance of the WebHeaderCollection class that contains header values associated with this response.
Exceptions
NotSupportedException NotSupportedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example displays all of the header name-value pairs returned in the WebResponse.

// Create a 'WebRequest' object with the specified url.


WebRequest myWebRequest = WebRequest.Create("http://www.contoso.com");

// Send the 'WebRequest' and wait for response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Display all the Headers present in the response received from the URl.
Console.WriteLine("
The following headers were received in the response");

// Display each header and it's key , associated with the response object.
for(int i=0; i < myWebResponse.Headers.Count; ++i)
Console.WriteLine("
Header Name:{0}, Header value :{1}",myWebResponse.Headers.Keys[i],myWebResponse.Headers[i]);

// Release resources of response object.


myWebResponse.Close();

Remarks
The Headers property contains the name-value header pairs returned in the response.
Note

The WebResponse class is an abstract class. The actual behavior of WebResponse instances at run time is determined
by the descendant class returned by WebRequest.GetResponse. For more information about default values and
exceptions, please see the documentation for the descendant classes, such as HttpWebResponse and FileWebResponse.
See WebHeaderCollectionWebHeaderCollection
Also
WebResponse.IDisposable.Dispose
I n this Article
When overridden in a derived class, releases all resources used by the WebResponse.
void IDisposable.Dispose ();

Exceptions
NotSupportedException
Any attempt is made to access the method, when the method is not overridden in a descendant class.
WebResponse.ISerializable.GetObjectData
I n this Article
Populates a SerializationInfo instance with the data that is needed to serialize WebResponse.
void ISerializable.GetObjectData (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);

Parameters
serializationInfo SerializationInfo
A SerializationInfo that will hold the serialized data for the WebResponse.
streamingContext StreamingContext
A StreamingContext that contains the destination of the serialized stream that is associated with the new
WebResponse.
WebResponse.IsFromCache WebResponse.IsFromCache
I n this Article
Gets a Boolean value that indicates whether this response was obtained from the cache.
public virtual bool IsFromCache { get; }
member this.IsFromCache : bool

Returns
Boolean Boolean
true if the response was taken from the cache; otherwise, false .

Remarks
The current cache policy and the presence of the requested resource in the cache determine whether a response can be
retrieved from the cache. Using cached responses usually improves application performance, but there is a risk that the
response in the cache does not match the response on the server. Use the CachePolicy property to set and the
RequestCachePolicy class to enumerate the current caching policy.
Note that getting this property can throw ObjectDisposedException.
WebResponse.IsMutuallyAuthenticated WebResponse.Is
MutuallyAuthenticated
I n this Article
Gets a Boolean value that indicates whether mutual authentication occurred.

public virtual bool IsMutuallyAuthenticated { get; }


member this.IsMutuallyAuthenticated : bool

Returns
Boolean Boolean
true if both client and server were authenticated; otherwise, false .

Examples
The following code example checks the value of this property.

// The following example uses the System, System.Net,


// and System.IO namespaces.

public static void RequestMutualAuth(Uri resource)


{
// Create a new HttpWebRequest object for the specified resource.
WebRequest request=(WebRequest) WebRequest.Create(resource);
// Request mutual authentication.
request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;
// Supply client credentials.
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
// Determine whether mutual authentication was used.
Console.WriteLine("Is mutually authenticated? {0}", response.IsMutuallyAuthenticated);
// Read and display the response.
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
Console.WriteLine(responseString);
// Close the stream objects.
streamResponse.Close();
streamRead.Close();
// Release the HttpWebResponse.
response.Close();
}

Remarks
To request mutual authentication, set the WebRequest.AuthenticationLevel property using the MutualAuthRequested
or MutualAuthRequired enumeration value. The default value for the WebRequest.AuthenticationLevel property
contains Delegation and MutualAuthRequested.
Note that getting this property can throw ObjectDisposedException.
WebResponse.ResponseUri WebResponse.ResponseUri
I n this Article
When overridden in a derived class, gets the URI of the Internet resource that actually responded to the request.
public virtual Uri ResponseUri { get; }
member this.ResponseUri : Uri

Returns
Uri Uri
An instance of the Uri class that contains the URI of the Internet resource that actually responded to the request.
Exceptions
NotSupportedException NotSupportedException
Any attempt is made to get or set the property, when the property is not overridden in a descendant class.

Examples
The following example uses the ResponseUri property to determine the location from which the WebResponse
originated.
Uri ourUri = new Uri(url);

// Create a 'WebRequest' object with the specified url.


WebRequest myWebRequest = WebRequest.Create(url);

// Send the 'WebRequest' and wait for response.


WebResponse myWebResponse = myWebRequest.GetResponse();

// Use "ResponseUri" property to get the actual Uri from where the response was attained.
if (ourUri.Equals(myWebResponse.ResponseUri))
Console.WriteLine("
Request Url : {0} was not redirected",url);
else
Console.WriteLine("
Request Url : {0} was redirected to {1}",url,myWebResponse.ResponseUri);
// Release resources of response object.
myWebResponse.Close();

Remarks
The ResponseUri property contains the URI of the Internet resource that actually provided the response data. This
resource might not be the originally requested URI if the underlying protocol allows redirection of the request.
Note

The WebResponse class is an abstract class. The actual behavior of WebResponse instances at run time is determined
by the descendant class returned by WebRequest.GetResponse. For more information about default values and
exceptions, please see the documentation for the descendant classes, such as HttpWebResponse and FileWebResponse.
WebResponse.SupportsHeaders WebResponse.Supports
Headers
I n this Article
Gets a value that indicates if headers are supported.

public virtual bool SupportsHeaders { get; }


member this.SupportsHeaders : bool

Returns
Boolean Boolean
Returns Boolean.
true if headers are supported; otherwise, false .

Remarks
This property is always true for .NET Framework 4.5.
WebResponse WebResponse
I n this Article

Overloads
WebResponse()
Initializes a new instance of the WebResponse class.

WebResponse(SerializationInfo, StreamingContext) Web


Response(SerializationInfo, StreamingContext) Initializes a new instance of the WebResponse class from the
specified instances of the SerializationInfo and
StreamingContext classes.

WebResponse()
Initializes a new instance of the WebResponse class.
protected WebResponse ();

Remarks
Applications do not call the WebResponse constructor directly; use the GetResponse method on a WebRequest
instance.

WebResponse(SerializationInfo, StreamingContext)
WebResponse(SerializationInfo, StreamingContext)
Initializes a new instance of the WebResponse class from the specified instances of the SerializationInfo and
StreamingContext classes.
protected WebResponse (System.Runtime.Serialization.SerializationInfo serializationInfo,
System.Runtime.Serialization.StreamingContext streamingContext);
new System.Net.WebResponse : System.Runtime.Serialization.SerializationInfo *
System.Runtime.Serialization.StreamingContext -> System.Net.WebResponse

Parameters
serializationInfo SerializationInfo SerializationInfo
An instance of the SerializationInfo class that contains the information required to serialize the new WebRequest
instance.
streamingContext StreamingContext StreamingContext
An instance of the StreamingContext class that indicates the source of the serialized stream that is associated with the
new WebRequest instance.
Exceptions
NotSupportedException NotSupportedException
Any attempt is made to access the constructor, when the constructor is not overridden in a descendant class.
Remarks
When implemented by a descendant class, this constructor implements the ISerializable interface for the WebResponse
descendant.
WebUtility WebUtility Class
Provides methods for encoding and decoding URLs when processing Web requests.

D eclaration
public static class WebUtility
type WebUtility = class

I nheritance H ierarchy
Object Object

Remarks
The HttpUtility class contains encoding and decoding utility methods for use with HTML -encode strings. The
System.Uri class also contains methods and properties that can be used for similar purposes.

Methods
HtmlDecode(String)
HtmlDecode(String)

Converts a string that has been HTML -encoded for HTTP transmission into a decoded string.

HtmlDecode(String, TextWriter)
HtmlDecode(String, TextWriter)

Converts a string that has been HTML -encoded into a decoded string, and sends the decoded string to a
TextWriter output stream.

HtmlEncode(String)
HtmlEncode(String)

Converts a string to an HTML -encoded string.

HtmlEncode(String, TextWriter)
HtmlEncode(String, TextWriter)

Converts a string into an HTML -encoded string, and returns the output as a TextWriter stream of output.

UrlDecode(String)
UrlDecode(String)

Converts a string that has been encoded for transmission in a URL into a decoded string.

UrlDecodeToBytes(Byte[], Int32, Int32)


UrlDecodeToBytes(Byte[], Int32, Int32)
Converts an encoded byte array that has been encoded for transmission in a URL into a decoded byte array.

UrlEncode(String)
UrlEncode(String)

Converts a text string into a URL -encoded string.

UrlEncodeToBytes(Byte[], Int32, Int32)


UrlEncodeToBytes(Byte[], Int32, Int32)

Converts a byte array into a URL -encoded byte array.

See Also
WebUtility.HtmlDecode WebUtility.HtmlDecode
I n this Article

Overloads
HtmlDecode(String) HtmlDecode(String)
Converts a string that has been HTML-encoded for HTTP
transmission into a decoded string.

HtmlDecode(String, TextWriter) HtmlDecode(String, TextWriter)


Converts a string that has been HTML-encoded into a
decoded string, and sends the decoded string to a TextWriter
output stream.

HtmlDecode(String) HtmlDecode(String)
Converts a string that has been HTML -encoded for HTTP transmission into a decoded string.
public static string HtmlDecode (string value);
static member HtmlDecode : string -> string

Parameters
value String String
The string to decode.
Returns
String String
A decoded string.
Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents;
HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are
encoded as &lt; and &gt; for HTTP transmission.
If the value parameter is null , then the returned decoded string is null . If the value parameter is an empty string,
then the returned decoded string is an empty string.
See HtmlEncode(String)HtmlEncode(String)
Also

HtmlDecode(String, TextWriter) HtmlDecode(String, TextWriter)


Converts a string that has been HTML -encoded into a decoded string, and sends the decoded string to a TextWriter
output stream.
public static void HtmlDecode (string value, System.IO.TextWriter output);
static member HtmlDecode : string * System.IO.TextWriter -> unit

Parameters
value String String
The string to decode.
output TextWriter TextWriter
A TextWriter stream of output.
Exceptions
ArgumentNullException ArgumentNullException
The output parameter cannot be null if the value parameter is not null .
Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents;
HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are
encoded as &lt; and &gt; for HTTP transmission.
See HtmlEncode(String, TextWriter)HtmlEncode(String, TextWriter)
Also
WebUtility.HtmlEncode WebUtility.HtmlEncode
I n this Article

Overloads
HtmlEncode(String) HtmlEncode(String)
Converts a string to an HTML-encoded string.

HtmlEncode(String, TextWriter) HtmlEncode(String, TextWriter)


Converts a string into an HTML-encoded string, and returns
the output as a TextWriter stream of output.

HtmlEncode(String) HtmlEncode(String)
Converts a string to an HTML -encoded string.
public static string HtmlEncode (string value);
static member HtmlEncode : string -> string

Parameters
value String String
The string to encode.
Returns
String String
An encoded string.
Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents;
HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are
encoded as &lt; and &gt; for HTTP transmission.
If the value parameter is null , then the returned encoded string is null . If the value parameter is an empty string,
then the returned encoded string is an empty string.
See HtmlDecode(String)HtmlDecode(String)
Also How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings

HtmlEncode(String, TextWriter) HtmlEncode(String, TextWriter)


Converts a string into an HTML -encoded string, and returns the output as a TextWriter stream of output.
public static void HtmlEncode (string value, System.IO.TextWriter output);
static member HtmlEncode : string * System.IO.TextWriter -> unit

Parameters
value String String
The string to encode.
output TextWriter TextWriter
A TextWriter output stream.
Exceptions
ArgumentNullException ArgumentNullException
The output parameter cannot be null if the value parameter is not null .
Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. HTML encoding converts characters that are not allowed in HTML into character-entity equivalents;
HTML decoding reverses the encoding. For example, when embedded in a block of text, the characters < and > are
encoded as &lt; and &gt; for HTTP transmission.
See HtmlDecode(String, TextWriter)HtmlDecode(String, TextWriter)
Also How to: Protect Against Script Exploits in a Web Application by Applying HTML Encoding to Strings
WebUtility.UrlDecode WebUtility.UrlDecode
I n this Article
Converts a string that has been encoded for transmission in a URL into a decoded string.
public static string UrlDecode (string encodedValue);
static member UrlDecode : string -> string

Parameters
encodedValue String String
A URL -encoded string to decode.
Returns
String String
A decoded string.

Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. URL encoding converts characters that are not allowed in a URL into equivalent hexadecimal escape
sequences. The UrlEncode method creates a URL -encoded string.
URL decoding replaces hexadecimal escape sequences with corresponding ASCII character equivalents. For example,
when embedded in a block of URL -encoded text, the escape sequences %3c and %3e are decoded into the characters
< and > .
WebUtility.UrlDecodeToBytes WebUtility.UrlDecodeTo
Bytes
I n this Article
Converts an encoded byte array that has been encoded for transmission in a URL into a decoded byte array.

public static byte[] UrlDecodeToBytes (byte[] encodedValue, int offset, int count);
static member UrlDecodeToBytes : byte[] * int * int -> byte[]

Parameters
encodedValue Byte[]
A URL -encoded Byte array to decode.
offset Int32 Int32
The offset, in bytes, from the start of the Byte array to decode.
count Int32 Int32
The count, in bytes, to decode from the Byte array.
Returns
Byte[]
A decoded Byte array.

Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. URL encoding converts characters that are not allowed in a URL into equivalent hexadecimal escape
sequences. The UrlEncodeToBytes method creates a URL -encoded byte array.
URL decoding replaces hexadecimal escape sequences with corresponding ASCII character equivalents. For example,
when embedded in a block of URL -encoded text, the escape sequences %3c and %3e are decoded into the characters
< and > .
WebUtility.UrlEncode WebUtility.UrlEncode
I n this Article
Converts a text string into a URL -encoded string.
public static string UrlEncode (string value);
static member UrlEncode : string -> string

Parameters
value String String
The text to URL -encode.
Returns
String String
A URL -encoded string.

Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. URL encoding replaces characters that are not allowed in a URL with character-entity equivalents
consisting of hexadecimal escape sequences. The converted string is expected to conform to the UTF -8 format.
URL encoding replaces all character codes except for letters, numbers, and the following punctuation characters:
- (minus sign)

_ (underscore)

. (period)

! (exclamation point)

* (asterisk)

( and ) (opening and closing parentheses)


For example, when embedded in a block of text to be transmitted in a URL, the characters < and > are encoded as
%3c and %3e .

The UrlDecode method reverses the encoding.


WebUtility.UrlEncodeToBytes WebUtility.UrlEncodeTo
Bytes
I n this Article
Converts a byte array into a URL -encoded byte array.

public static byte[] UrlEncodeToBytes (byte[] value, int offset, int count);
static member UrlEncodeToBytes : byte[] * int * int -> byte[]

Parameters
value Byte[]
The Byte array to URL -encode.
offset Int32 Int32
The offset, in bytes, from the start of the Byte array to encode.
count Int32 Int32
The count, in bytes, to encode from the Byte array.
Returns
Byte[]
An encoded Byte array.

Remarks
If characters such as blanks and punctuation are passed in an HTTP stream, they might be misinterpreted at the
receiving end. URL encoding replaces characters that are not allowed in a URL with character-entity equivalents
consisting of hexadecimal escape sequences. The converted string is expected to conform to the UTF -8 format.
URL encoding replaces all character codes except for letters, numbers, and the following punctuation characters:
- (minus sign)

_ (underscore)

. (period)

! (exclamation point)

* (asterisk)

' (single quotation mark)

( and ) (opening and closing parentheses)


For example, when embedded in a block of text to be transmitted in a URL, the characters < and > are encoded as
%3c and %3e .

The UrlDecodeToBytes method reverses the encoding.


WriteStreamClosedEventArgs WriteStreamClosedEvent
Args Class
Provides data for the WriteStreamClosed event.

D eclaration
public class WriteStreamClosedEventArgs : EventArgs
type WriteStreamClosedEventArgs = class
inherit EventArgs

I nheritance H ierarchy
Object Object
EventArgs EventArgs

Constructors
WriteStreamClosedEventArgs()
WriteStreamClosedEventArgs()

Initializes a new instance of the WriteStreamClosedEventArgs class.

Properties
Error
Error

Gets the error value when a write stream is closed.


WriteStreamClosedEventArgs.Error WriteStreamClosed
EventArgs.Error
I n this Article
Gets the error value when a write stream is closed.

[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public Exception Error { get; }
member this.Error : Exception

Returns
Exception Exception
Returns Exception.
Attributes ObsoleteAttribute

Remarks
If the Error property is an Exception object, the asynchronous operation did not complete correctly.
WriteStreamClosedEventArgs
I n this Article
Initializes a new instance of the WriteStreamClosedEventArgs class.
[System.Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used
directly from your code.", true)]
public WriteStreamClosedEventArgs ();

Attributes ObsoleteAttribute
WriteStreamClosedEventHandler WriteStreamClosed
EventHandler Delegate
Represents the method that will handle the WriteStreamClosed event of a WebClient.

D eclaration
public delegate void WriteStreamClosedEventHandler(object sender, WriteStreamClosedEventArgs e);
type WriteStreamClosedEventHandler = delegate of obj * WriteStreamClosedEventArgs -> unit

I nheritance H ierarchy
Object Object
Delegate Delegate

You might also like