Class StringExtensions
- Namespace
- Cuemon.Extensions.IO
- Assembly
- Cuemon.Extensions.IO.dll
Extension methods for the string class.
public static class StringExtensions
- Inheritance
-
StringExtensions
Examples
StringExtensions in the IO namespace converts strings into Stream and TextReader instances for stream-based processing. This example starts with a JSON string {"key":"value"}, calls ToStream with a UTF-8 encoding configuration, ToStreamAsync for the asynchronous variant, and ToTextReader for direct text reader access. Key steps include verifying the stream has positive length, reading back the async stream's content with ToEncodedStringAsync, and reading the text reader content with ReadToEnd. Console output confirms the stream length is greater than zero, the async round-trip matches the original JSON, and the text reader reads the expected content.
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using Cuemon.Extensions.IO;
namespace MyApp.Examples
{
public static class StringExtensionsExample
{
public static async Task DemonstrateAsync()
{
const string json = "{\"key\":\"value\"}";
using Stream stream = json.ToStream(options =>
{
options.Encoding = Encoding.UTF8;
});
using Stream asyncStream = await json.ToStreamAsync();
using TextReader reader = json.ToTextReader();
Console.WriteLine(stream.Length > 0);
Console.WriteLine((await asyncStream.ToEncodedStringAsync()) == json);
Console.WriteLine(reader.ReadToEnd());
}
}
}
Methods
ToStream(string, Action<EncodingOptions>)
Converts the specified value to a Stream.
public static Stream ToStream(this string value, Action<EncodingOptions> setup = null)
Parameters
valuestringThe string to extend.
setupAction<EncodingOptions>The EncodingOptions which may be configured.
Returns
Remarks
IEncodingOptions will be initialized with DefaultPreambleSequence and DefaultEncoding.
Exceptions
- ArgumentNullException
valuecannot be null.- InvalidEnumArgumentException
setupwas initialized with an invalid Preamble.
ToStreamAsync(string, Action<AsyncEncodingOptions>)
Converts the specified value to a Stream.
public static Task<Stream> ToStreamAsync(this string value, Action<AsyncEncodingOptions> setup = null)
Parameters
valuestringThe string to extend.
setupAction<AsyncEncodingOptions>The AsyncEncodingOptions which may be configured.
Returns
- Task<Stream>
A task that represents the asynchronous operation. The task result contains a Stream containing the result of the specified
value.
Remarks
IEncodingOptions will be initialized with DefaultPreambleSequence and DefaultEncoding.
Exceptions
- ArgumentNullException
valuecannot be null.- InvalidEnumArgumentException
setupwas initialized with an invalid Preamble.
ToTextReader(string)
Converts the specified value to a TextReader object.
public static TextReader ToTextReader(this string value)
Parameters
Returns
- TextReader
A TextReader initialized with
value.