String - ToByteArray
A string extension method that converts the string object to a byte array.
public static string FileName = "test.txt"; public static void Main() { var text = @"<!DOCTYPE html> <html> <body> <h1>This is <b>bold</b> heading</h1> <p>This is <u>underlined</u> paragraph</p> <h2>This is <i>italic</i> heading</h2> </body> </html> "; // C# Extension Method: String - ToByteArray byte[] bytes = text.ToByteArray(); //C# Extension Method: String - ToFileInfo var file = FileName.ToFileInfo(); // C# Extension Method: FileInfo - WriteAllBytes file.WriteAllBytes(bytes); Console.WriteLine(file.ReadAllText()); }
View Source
using System; using System.Text; public static partial class Extensions { /// <summary> /// A string extension method that converts the @this to a byte array. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>@this as a byte[].</returns> public static byte[] ToByteArray(this string @this) { Encoding encoding = Activator.CreateInstance<ASCIIEncoding>(); return encoding.GetBytes(@this); } }