Convert a String to a Byte Array in C#

This article will introduce a method to convert a string to a byte array in C#.

  • Use the GetBytes() method

Use the GetBytes() Method to Convert a String to a Byte Array in C

In C#, we can use the GetBytes() method of Encoding class to convert a string to a byte array. There are multiple encodings that we can convert into a byte array. These encodings are ASCII, Unicode, UTF32, etc. This method has multiple overloads. We will use the following overload in this case. The correct syntax to use this method is as follows.

Encoding.GetBytes(String stringName);

This overload of the method GetBytes() has one parameter only. The detail of its parameter is as follows.

Parameters Description
stringName mandatory This is the string that we want to convert to a byte array

This function returns a byte array representing the given string in bytes.

The program below shows how we can use the GetBytes() method to convert a string to a byte array.

using System;
using System.Text;

class StringToByteArray {
  static void Main(string[] args) {
    string myString = "This is a string.";
    byte[] byteArray = Encoding.ASCII.GetBytes(myString);
    Console.WriteLine("The Byte Array is:");
    foreach(byte bytes in byteArray) {
      Console.WriteLine(bytes);
    }
  }
}

Output:

The Byte Array is:
84
104
105
115
32
105
115
32
97
32
115
116
114
105
110
103
46
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Csharp String

  • Convert String to JSON Object in C#
  • Enum Strings in C#
  • Related Article - Csharp Array

  • Format a String to Currency in C#
  • C# Convert String to Enum