Class NetworkHelper
Provides various network helper extension methods.
public static class NetworkHelper
- Inheritance
-
NetworkHelper
- Inherited Members
Fields
MtuSize
Gets the Maximum Transmission Unit size.
public const int MtuSize = 1600
Field Value
Methods
ApplyChromeAgent(HttpClient)
Applies a Chrome user agent to the HttpClient.
public static void ApplyChromeAgent(this HttpClient client)
Parameters
client
HttpClientThe HttpClient instance.
CheckContainsUrl(string)
Checks if the URL contains any of the predefined URL parts.
public static bool CheckContainsUrl(this string url)
Parameters
url
stringThe URL to check.
Returns
- bool
true
if the URL contains one of the parts; otherwise,false
.
CheckUrl(string, bool, bool, bool)
Checks and cleans a URL by converting to Latin characters, screening, and clearing unsafe characters.
public static string CheckUrl(this string str, bool latin = true, bool screen = true, bool clear = true)
Parameters
str
stringThe URL string to check.
latin
boolif set to
true
converts characters to Latin.screen
boolif set to
true
performs light screening.clear
boolif set to
true
clears unsafe URL characters.
Returns
- string
The processed URL.
ClearUrl(string)
Removes unsafe characters from the URL.
public static string ClearUrl(this string url)
Parameters
url
stringThe URL to clear.
Returns
- string
The cleared URL string.
Connect(TcpClient, EndPoint)
Connects the TcpClient to the specified endpoint.
public static void Connect(this TcpClient client, EndPoint address)
Parameters
CreateHttpRequestException(HttpStatusCode, string)
Creates an HttpRequestException for the specified HTTP status code and message.
public static HttpRequestException CreateHttpRequestException(this HttpStatusCode code, string message)
Parameters
code
HttpStatusCodeThe HTTP status code.
message
stringThe error message.
Returns
- HttpRequestException
An instance of HttpRequestException.
DecodeFromHtml(string)
Decodes the specified HTML-encoded text.
public static string DecodeFromHtml(this string text)
Parameters
text
stringThe text to decode.
Returns
- string
The decoded string.
DecodeUrl(string)
Decodes the specified URL.
public static string DecodeUrl(this string url)
Parameters
url
stringThe URL to decode.
Returns
- string
The decoded URL string.
EncodeToHtml(string)
Encodes the specified text into its HTML-encoded representation.
public static string EncodeToHtml(this string text)
Parameters
text
stringThe text to encode.
Returns
- string
The HTML-encoded string.
EncodeUrl(string)
Encodes a URL using UTF8 encoding.
public static string EncodeUrl(this string url)
Parameters
url
stringThe URL to encode.
Returns
- string
The encoded URL string.
EncodeUrlUpper(string)
Encodes a URL ensuring uppercase encoding.
public static string EncodeUrlUpper(this string url)
Parameters
url
stringThe URL to encode.
Returns
- string
The URL encoded in uppercase.
ExcludeEmpty(NameValueCollection)
Enumerates key-value pairs from the collection, excluding empty keys.
public static IEnumerable<(string key, string value)> ExcludeEmpty(this NameValueCollection col)
Parameters
col
NameValueCollectionThe name-value collection.
Returns
- IEnumerable<(string key, string value)>
An enumerable of non-empty key-value pairs.
Format<T>(T, bool)
Formats the value as a string with optional URL encoding.
public static string Format<T>(this T value, bool encode)
Parameters
value
TThe value to format.
encode
boolWhether to URL encode the result.
Returns
- string
The formatted string.
Type Parameters
T
The type of the value.
GetDelay(RetryPolicyInfo, int)
Calculates the delay for a retry based on the current attempt number.
public static TimeSpan GetDelay(this RetryPolicyInfo policy, int attemptNumber)
Parameters
policy
RetryPolicyInfoThe retry policy information.
attemptNumber
intThe current attempt number.
Returns
- TimeSpan
A TimeSpan representing the delay.
GetGravatarToken(string)
Computes the Gravatar token for the specified email.
public static string GetGravatarToken(this string email)
Parameters
email
stringThe email address.
Returns
- string
The computed Gravatar token.
GetGravatarUrl(string, int)
Constructs the Gravatar URL using the provided token and size.
public static string GetGravatarUrl(this string token, int size)
Parameters
Returns
- string
The full Gravatar image URL.
IsConnected(Socket, int)
Determines whether the specified socket is connected.
public static bool IsConnected(this Socket socket, int timeOut = 1)
Parameters
Returns
- bool
true
if the socket is connected; otherwise,false
.
IsImage(string)
Determines whether the specified file name represents an image.
public static bool IsImage(this string fileName)
Parameters
fileName
stringThe file name to check.
Returns
- bool
true
if the file is an image; otherwise,false
.
IsImageVector(string)
Determines whether the specified file name represents a vector image.
public static bool IsImageVector(this string fileName)
Parameters
fileName
stringThe file name to check.
Returns
- bool
true
if the file is a vector image; otherwise,false
.
IsInSubnet(IPAddress, string)
Determines whether the specified IPv4 or IPv6 address is part of the given subnet.
public static bool IsInSubnet(this IPAddress address, string subnetMask)
Parameters
address
IPAddressThe IP address to check.
subnetMask
stringThe subnet mask in "IP/PrefixLength" format.
Returns
- bool
true
if the address is in the subnet; otherwise,false
.
IsLocal(EndPoint)
Determines whether the specified endpoint is local.
public static bool IsLocal(this EndPoint endPoint)
Parameters
endPoint
EndPointThe endpoint to check.
Returns
- bool
true
if the endpoint is local; otherwise,false
.
IsLocalIpAddress(EndPoint)
Checks whether the specified endpoint's IP addresses include a local address.
public static bool IsLocalIpAddress(this EndPoint endPoint)
Parameters
endPoint
EndPointThe endpoint to check.
Returns
- bool
true
if a local IP address is found; otherwise,false
.
IsLocalhost(Uri)
Determines whether the specified Uri represents localhost.
public static bool IsLocalhost(this Uri url)
Parameters
url
UriThe Uri to check.
Returns
- bool
true
if the Uri is localhost; otherwise,false
.
IsLoopback(IPAddress)
Determines if the specified IPAddress represents a loopback address.
public static bool IsLoopback(this IPAddress address)
Parameters
address
IPAddressThe IPAddress to check.
Returns
- bool
true
if the IPAddress is loopback; otherwise,false
.
IsUrlSafeChar(char)
Determines whether the specified character is safe for URLs.
public static bool IsUrlSafeChar(this char ch)
Parameters
ch
charThe character to check.
Returns
- bool
true
if the character is URL safe; otherwise,false
.
JoinMulticast(Socket, MulticastSourceAddress)
Joins the specified source-specific multicast group.
public static void JoinMulticast(this Socket socket, MulticastSourceAddress address)
Parameters
socket
SocketThe socket to configure.
address
MulticastSourceAddressThe multicast source address configuration.
JoinMulticast(Socket, IPAddress)
Joins the specified multicast group using the provided IP address.
public static void JoinMulticast(this Socket socket, IPAddress address)
Parameters
LeaveMulticast(Socket, MulticastSourceAddress)
Leaves the specified source-specific multicast group.
public static void LeaveMulticast(this Socket socket, MulticastSourceAddress address)
Parameters
socket
SocketThe socket to configure.
address
MulticastSourceAddressThe multicast source address configuration.
LeaveMulticast(Socket, IPAddress)
Leaves the specified multicast group using the provided IP address.
public static void LeaveMulticast(this Socket socket, IPAddress address)
Parameters
ParseUrl(string)
Parses the query string from the URL.
public static NameValueCollection ParseUrl(this string url)
Parameters
url
stringThe URL query string.
Returns
- NameValueCollection
A collection of query string parameters.
Read(Socket, byte[], int, int)
Reads the specified number of bytes from the socket into the provided buffer.
public static void Read(this Socket socket, byte[] buffer, int offset, int len)
Parameters
socket
SocketThe source socket.
buffer
byte[]The buffer to store the data.
offset
intThe offset in the buffer.
len
intThe number of bytes to read.
SetBearer(HttpClient, SecureString)
Sets a bearer token for authorization on the HttpClient.
public static void SetBearer(this HttpClient client, SecureString token)
Parameters
client
HttpClientThe HttpClient instance.
token
SecureStringThe secure bearer token.
SetStatusCodePhrase(HttpStatusCode, string)
Sets a custom phrase for a specific HTTP status code.
public static void SetStatusCodePhrase(HttpStatusCode code, string str)
Parameters
code
HttpStatusCodeThe HTTP status code.
str
stringThe phrase to associate with the status code.
ToQueryString<TValue>(IEnumerable<KeyValuePair<string, TValue>>, bool)
Converts a sequence of key-value pairs into a query string.
public static string ToQueryString<TValue>(this IEnumerable<KeyValuePair<string, TValue>> args, bool encodeValue = false)
Parameters
args
IEnumerable<KeyValuePair<string, TValue>>The key-value pairs.
encodeValue
boolWhether to encode the value.
Returns
- string
A query string representation of the key-value pairs.
Type Parameters
TValue
The type of the value.
ToQueryString<TValue>(IEnumerable<(string key, TValue value)>, bool)
Converts a sequence of tuple key-value pairs into a query string.
public static string ToQueryString<TValue>(this IEnumerable<(string key, TValue value)> args, bool encodeValue = false)
Parameters
args
IEnumerable<(string key, TValue value)>The tuple key-value pairs.
encodeValue
boolWhether to encode the value.
Returns
- string
A query string representation of the tuples.
Type Parameters
TValue
The type of the value.
ToSsl(Stream, SslProtocols, bool, bool, string, string, SecureString, RemoteCertificateValidationCallback, LocalCertificateSelectionCallback)
Converts the provided stream into an SSL stream with the specified options.
public static SslStream ToSsl(this Stream stream, SslProtocols sslProtocol, bool checkCertificateRevocation, bool validateRemoteCertificates, string targetHost, string sslCertificate, SecureString sslCertificatePassword, RemoteCertificateValidationCallback certificateValidationCallback = null, LocalCertificateSelectionCallback certificateSelectionCallback = null)
Parameters
stream
StreamThe underlying stream.
sslProtocol
SslProtocolsThe SSL protocol to use.
checkCertificateRevocation
boolWhether to check certificate revocation.
validateRemoteCertificates
boolWhether to validate remote certificates.
targetHost
stringThe target host name.
sslCertificate
stringThe certificate file path.
sslCertificatePassword
SecureStringThe certificate password.
certificateValidationCallback
RemoteCertificateValidationCallbackOptional certificate validation callback.
certificateSelectionCallback
LocalCertificateSelectionCallbackOptional certificate selection callback.
Returns
- SslStream
An authenticated SslStream.
TryExtractEncoding(string)
Attempts to extract an Encoding from the Content-Type header.
public static Encoding TryExtractEncoding(this string contentType)
Parameters
contentType
stringThe Content-Type header value.
Returns
- Encoding
An Encoding if found; otherwise,
null
.
TryGetSocketError(Exception)
Attempts to retrieve the underlying socket error from an exception.
public static SocketError? TryGetSocketError(this Exception ex)
Parameters
ex
ExceptionThe exception to inspect.
Returns
- SocketError?
The SocketError if found; otherwise,
null
.
TryGetStatusCode(HttpRequestException)
Attempts to retrieve an HTTP status code from the specified HttpRequestException.
public static HttpStatusCode? TryGetStatusCode(this HttpRequestException ex)
Parameters
ex
HttpRequestExceptionThe HttpRequestException to analyze.
Returns
- HttpStatusCode?
The associated HttpStatusCode if found; otherwise,
null
.
TryRepeat<T>(RetryPolicyInfo, Func<Task<T>>, int, CancellationToken)
Attempts to repeatedly execute a function based on the retry policy.
public static Task<T> TryRepeat<T>(this RetryPolicyInfo policy, Func<Task<T>> handler, int maxCount, CancellationToken cancellationToken)
Parameters
policy
RetryPolicyInfoThe retry policy information.
handler
Func<Task<T>>The asynchronous function to execute.
maxCount
intThe maximum number of attempts.
cancellationToken
CancellationTokenThe cancellation token.
Returns
- Task<T>
The result of the function if successful.
Type Parameters
T
The type of the result.
UrlEncodeToUpperCase(string)
URL encodes the string ensuring that hexadecimal values are in uppercase.
public static string UrlEncodeToUpperCase(this string url)
Parameters
url
stringThe URL to encode.
Returns
- string
An uppercase URL encoded string.
Wait(Socket, int)
Waits for data availability on the socket.
public static bool Wait(this Socket socket, int timeOut)
Parameters
Returns
- bool
true
if data is available; otherwise,false
.
XmlEscape(string)
Escapes special XML characters in the content.
public static string XmlEscape(this string content)
Parameters
content
stringThe content to escape.
Returns
- string
The escaped XML string.