Search code examples
c#encodingbytestringbuilder

StringBuilder and byte conversion


I have the following code:

StringBuilder data = new StringBuilder();
for (int i = 0; i < bytes1; i++)
{ 
    data.Append("a"); 
}
byte[] buffer = Encoding.ASCII.GetBytes(data);

But I get this error:

cannot convert from 'System.Text.StringBuilder' to 'char[]'
The best overloaded method match for 'System.Text.Encoding.GetBytes(char[])'
has some invalid arguments

Solution

  • The following code will fix your issue.

    StringBuilder data = new StringBuilder();
    for (int i = 0; i < bytes1; i++)
    { data.Append("a"); }
    byte[] buffer = Encoding.ASCII.GetBytes(data.ToString());
    

    The problem is that you are passing a StringBuilder to the GetBytes function when you need to passing the string result from the StringBuilder.