StringBuilder and byte conversion

R.Vector picture R.Vector · Feb 2, 2012 · Viewed 53.3k times · Source

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

Answer

Scott Smith picture Scott Smith · Feb 2, 2012

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.