A sample usage is
string sample = "This is a simple string"; byte[] content = Encoding.ASCII.GetBytes(sample);
Note that this method only works if the string is with the ASCII format.
The framework supports other encodings (UTF8, Unicode, UTF32, ...) but a more generic method is needed.
The ideal solution if to don't need to worry about the encoding if the bytes don't need to be interpreted.
A use case for this solution is to transfer a file from a web server to a browser.
static byte[] GetBytes(string value) { byte[] bytes = null; using (var memoryStream = new MemoryStream()) { using (var streamWriter = new StreamWriter(memoryStream, Encoding.Default)) { streamWriter.Write(value); streamWriter.Flush(); streamWriter.Close(); bytes = memoryStream.ToArray(); } } return bytes; }
But this solution also uses the Encoding.Default for the StreamWriter.
The Enconding can also be performed as:
string sample = "This is a simple string"; byte[] content = Encoding.Default.GetBytes(sample);
Welcome the the encondig hell!!